Skip to content

Commit 53c04cf

Browse files
authored
Create Rat_in_a_Maze.cpp
1 parent 18eba0f commit 53c04cf

1 file changed

Lines changed: 77 additions & 0 deletions

File tree

Backtracking/Rat_in_a_Maze.cpp

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
// https://practice.geeksforgeeks.org/problems/rat-in-a-maze-problem/1
2+
3+
#include <bits/stdc++.h>
4+
using namespace std;
5+
6+
class Solution{
7+
public:
8+
9+
vector <string> v;
10+
bool check (int x, int y, int n, vector<vector<int>> &m, char ch)
11+
{
12+
if(ch=='U')
13+
x--;
14+
else if(ch=='D')
15+
x++;
16+
else if(ch=='R')
17+
y++;
18+
else
19+
y--;
20+
21+
if(x<n && y<n && x>=0 && y>=0 && m[x][y]==1)
22+
return true;
23+
return false;
24+
}
25+
26+
void rec(vector<vector<int>> &m,int n,int x,int y,string s)
27+
{
28+
string temp = s;
29+
if(x==n-1 && y==n-1)
30+
{v.push_back(s);return ;}
31+
if(check(x,y,n,m,'U')==false && check(x,y,n,m,'D')==false && check(x,y,n,m,'R')==false && check(x,y,n,m,'L')==false)
32+
{
33+
return;
34+
}
35+
if(check(x,y,n,m,'U'))
36+
{
37+
s = s+'U';
38+
m[x-1][y] = 0;
39+
rec(m,n,x-1,y,s);
40+
m[x-1][y] = 1;
41+
s = temp;
42+
}
43+
if(check(x,y,n,m,'D'))
44+
{
45+
s = s+'D';
46+
m[x+1][y] = 0;
47+
rec(m,n,x+1,y,s);
48+
m[x+1][y] = 1;
49+
s = temp;
50+
}
51+
if(check(x,y,n,m,'R'))
52+
{
53+
s = s+'R';
54+
m[x][y+1] = 0;
55+
rec(m,n,x,y+1,s);
56+
m[x][y+1] = 1;
57+
s = temp;
58+
}
59+
if(check(x,y,n,m,'L'))
60+
{
61+
s = s+'L';
62+
m[x][y-1] = 0;
63+
rec(m,n,x,y-1,s);
64+
m[x][y-1] = 1;
65+
s = temp;
66+
}
67+
}
68+
69+
vector<string> findPath(vector<vector<int>> &m, int n) {
70+
71+
if(m[0][0]==0)
72+
return v;
73+
m[0][0] = 0;
74+
rec(m,n,0,0,"");
75+
return v;
76+
}
77+
};

0 commit comments

Comments
 (0)