Skip to content

Commit eaa82e4

Browse files
authored
Merge pull request #489 from harshita9621/master
Backtracking Rat in a Maze
2 parents cff1607 + 982cae2 commit eaa82e4

File tree

1 file changed

+118
-0
lines changed

1 file changed

+118
-0
lines changed
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
/* Rat In a Maze
2+
---------------------------------------------------------------------
3+
4+
Problem: Given a maze(2D matrix) with obstacles, starting from (0,0) you have to
5+
reach (n-1, n-1). If you are currently on (x,y), you can move to (x+1,y) or (x,y+1).
6+
You can not move to the walls.
7+
Idea: Try all the possible paths to see if you can reach (n-1,n-1)
8+
9+
--------------------------------------------------------------------------------
10+
11+
Input:
12+
----
13+
0 denotes wall, 1 denotes free path
14+
two numbers n, m
15+
Next n lines contain m numbers (0 or 1)
16+
17+
Output:
18+
--------
19+
Print 1 if rat can reach (n-1,m-1)
20+
Print 0 if it can not reach (n-1,m-1)
21+
22+
------------------------
23+
24+
Test Case 1:
25+
26+
Input:
27+
5 5
28+
1 0 1 0 1
29+
1 1 1 1 1
30+
0 1 0 1 0
31+
1 0 0 1 1
32+
1 1 1 0 1
33+
34+
Output:
35+
36+
1 0 0 0 0
37+
1 1 1 1 0
38+
0 0 0 1 0
39+
0 0 0 1 1
40+
0 0 0 0 1
41+
42+
*/
43+
44+
45+
#include <iostream>
46+
using namespace std;
47+
48+
bool isSafe(int **arr, int x, int y, int n){
49+
if(x<n && y<n && arr[x][y] == 1){
50+
return true;
51+
}
52+
return false;
53+
}
54+
55+
bool ratinMaze(int **arr, int x, int y,int n, int** solArr){
56+
57+
if((x== (n-1)) && (y== (n-1))){
58+
solArr[x][y]=1;
59+
return true;
60+
}
61+
62+
if(isSafe(arr,x,y,n)){
63+
solArr[x][y]==1;
64+
if(ratinMaze(arr,x+1,y,n,solArr)){
65+
return true;
66+
}
67+
if(ratinMaze(arr,x,y+1,n,solArr)){
68+
return true;
69+
}
70+
71+
solArr[x][y]=0; //backtracking
72+
return false;
73+
}
74+
return false;
75+
76+
}
77+
78+
int main(){
79+
80+
int n;
81+
cin>>n;
82+
83+
int** arr=new int*[n];
84+
for(int i=0;i<n;i++){
85+
arr[i]=new int[n];
86+
}
87+
88+
for(int i=0;i<n;i++){
89+
for(int j=0;j<n;j++){
90+
cin>>arr[i][j];
91+
}
92+
}
93+
94+
int** solArr=new int*[n];
95+
for(int i=0;i<n;i++){
96+
solArr[i]=new int[n];
97+
for(int j=0;j<n;j++){
98+
solArr[i][j]=0;
99+
}
100+
101+
}
102+
103+
if(ratinMaze(arr,0,0,n,solArr)){
104+
for(int i=0;i<n;i++){
105+
for(int j=0;j<n;j++){
106+
cout<<solArr[i][j]<<" ";
107+
} cout<<endl;
108+
}
109+
110+
}
111+
112+
113+
return 0;
114+
}
115+
116+
/* Time Complexity: O(2n)
117+
Space Complexity: O(2n)
118+
*/

0 commit comments

Comments
 (0)