# 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

Live Demo

#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

Updated on: 17-Apr-2020

134 Views