Skip to content

Commit 9946690

Browse files
authored
Create Rat_in_a_maize.cpp
1 parent 633aa8a commit 9946690

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

Backtracking/Rat_in_a_maize.cpp

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
#include<bits/stdc++.h>
2+
int maze[100][100];
3+
int ar[100][100];
4+
5+
void explore(int n,int row,int col)
6+
{
7+
8+
if(row==n-1 and col==n-1)
9+
{
10+
//base case
11+
maze[row][col]=1;
12+
for(int i=0;i<n;i++)
13+
for(int j=0;j<n;j++)
14+
cout<<maze[i][j]<<" ";
15+
cout<<endl;
16+
maze[row][col]=0;
17+
return;
18+
}
19+
20+
if(col+1!=n and ar[row][col+1]!=0 and maze[row][col+1]!=1)
21+
{
22+
maze[row][col+1]=1;
23+
explore(n,row,col+1);
24+
maze[row][col+1]=0;
25+
}
26+
if(col-1!=-1 and ar[row][col-1]!=0 and maze[row][col-1]!=1)
27+
{
28+
maze[row][col-1]=1;
29+
explore(n,row,col-1);
30+
maze[row][col-1]=0;
31+
}
32+
if(row+1!=n and ar[row+1][col]!=0 and maze[row+1][col]!=1)
33+
{
34+
maze[row+1][col]=1;
35+
explore(n,row+1,col);
36+
maze[row+1][col]=0;
37+
}
38+
if(row-1!=-1 and ar[row-1][col]!=0 and maze[row-1][col]!=1)
39+
{
40+
maze[row-1][col]=1;
41+
explore(n,row-1,col);
42+
maze[row-1][col]=0;
43+
}
44+
}
45+
46+
void findpath(int n)
47+
{
48+
memset(maze,0,sizeof(maze));
49+
maze[0][0]=1;
50+
explore(n,0,0);
51+
}
52+
void ratInAMaze(int arr[][20], int n){
53+
54+
for(int i=0;i<n;i++)
55+
for(int j=0;j<n;j++)
56+
ar[i][j]=arr[i][j];
57+
findpath(n);
58+
}

0 commit comments

Comments
 (0)