forked from Arunjay126/Hacktoberfest-21
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maze.cpp
105 lines (50 loc) · 1.39 KB
/
maze.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include<iostream>
#define N 5
using namespace std;
int maze[N][N] = {
{1, 0, 0, 0, 0},
{1, 1, 0, 1, 0},
{0, 1, 1, 1, 0},
{0, 0, 0, 1, 0},
{1, 1, 1, 1, 1}
};
int sol[N][N]; //final solution of the maze path is stored here
void showPath() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
cout << sol[i][j] << " ";
cout << endl;
}
}
bool isValidPlace(int x, int y) {//function to check place is inside the maze and have value 1
if(x >= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1)
return true;
return false;
}
bool solveRatMaze(int x, int y) {
if(x == N-1 && y == N-1) { //when (x,y) is the bottom right room
sol[x][y] = 1;
return true;
}
if(isValidPlace(x, y) == true) { //check whether (x,y) is valid or not
sol[x][y] = 1; //set 1, when it is valid place
if (solveRatMaze(x+1, y) == true) //find path by moving right direction
return true;
if (solveRatMaze(x, y+1) == true) //when x direction is blocked, go for bottom direction
return true;
sol[x][y] = 0; //if both are closed, there is no path
return false;
}
return false;
}
bool findSolution() {
if(solveRatMaze(0, 0) == false) {
cout << "There is no path";
return false;
}
showPath();
return true;
}
int main() {
findSolution();
}