
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Possibility of Moving Out of Maze in C++
In this problem, we are given a maze of n integers, each integer indicates the number of moves to be done. Along with the direction indicated using ‘>’ and ‘<’. Our task is to find whether it is possible to move out of the maze or not if the starting point is the position at 0 indexes.
Let’s take an example to understand the problem
Input −
3 2 1 1 4 > < > >
Output − YES
Explanation − moving from start, we will move 2 positions ahead, then 1 position ahead, then 4 positions ahead. This will move our of the maze.
To solve this problem, we will check whether moving out of the maze is possible or not. For this either we need to go below 0 or above n. Starting from 0, we will process the direction based on the sign by given integer places. And check if the end is reached.
One more condition that can arise is an infinite loop, i.e. the condition when the user never breaks out of the maze, this is when we come back to a visiting position. So, to check this condition we will mark all visited places.
Example
Program to show the implementation of our solution
#include <iostream> using namespace std; void isMazeSolvable (int a[], int n, string s){ int mark[n] = {0}; int start = 0; int possible = 1; while (start >= 0 && start < n){ if (s == "<"){ if (mark[start] == 0){ mark[start] = 1; start -= a[start]; } else { possible = 0; break; } } else { if (mark[start] == 0){ mark[start] = 1; start += a[start]; } else { possible = 0; break; } } } if (possible == 0) cout << "It stays inside the maze forever"; else cout << "It will come out of the maze"; } int main (){ int n = 3; string s = ">><"; int a[] = { 1, 2, 4 }; isMazeSolvable (a, n, s); }
Output
It will come out of the maze