Skip to content

Commit eb8d573

Browse files
committed
Backtracking Rat in a Maze.cpp
1 parent f8326e7 commit eb8d573

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
#include <iostream>
2+
using namespace std;
3+
4+
bool isSafe(int **arr, int x, int y, int n){
5+
if(x<n && y<n && arr[x][y] == 1){
6+
return true;
7+
}
8+
return false;
9+
}
10+
11+
bool ratinMaze(int **arr, int x, int y,int n, int** solArr){
12+
13+
if((x== (n-1)) && (y== (n-1))){
14+
solArr[x][y]=1;
15+
return true;
16+
}
17+
18+
if(isSafe(arr,x,y,n)){
19+
solArr[x][y]==1;
20+
if(ratinMaze(arr,x+1,y,n,solArr)){
21+
return true;
22+
}
23+
if(ratinMaze(arr,x,y+1,n,solArr)){
24+
return true;
25+
}
26+
27+
solArr[x][y]=0; //backtracking
28+
return false;
29+
}
30+
return false;
31+
32+
}
33+
34+
int main(){
35+
36+
int n;
37+
cin>>n;
38+
39+
int** arr=new int*[n];
40+
for(int i=0;i<n;i++){
41+
arr[i]=new int[n];
42+
}
43+
44+
for(int i=0;i<n;i++){
45+
for(int j=0;j<n;j++){
46+
cin>>arr[i][j];
47+
}
48+
}
49+
50+
int** solArr=new int*[n];
51+
for(int i=0;i<n;i++){
52+
solArr[i]=new int[n];
53+
for(int j=0;j<n;j++){
54+
solArr[i][j]=0;
55+
}
56+
57+
}
58+
59+
if(ratinMaze(arr,0,0,n,solArr)){
60+
for(int i=0;i<n;i++){
61+
for(int j=0;j<n;j++){
62+
cout<<solArr[i][j]<<" ";
63+
} cout<<endl;
64+
}
65+
66+
}
67+
68+
69+
return 0;
70+
}

0 commit comments

Comments
 (0)