forked from ashvish183/Hacktoberfest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRat_in_a_Maze.cpp
66 lines (54 loc) · 1.58 KB
/
Rat_in_a_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
#include <bits/stdc++.h>
using namespace std;
class Solution {
void findPathHelper(int i, int j, vector < vector < int >> & a, int n, vector < string > & ans, string move,
vector < vector < int >> & vis) {
if (i == n - 1 && j == n - 1) {
ans.push_back(move);
return;
}
// downward
if (i + 1 < n && !vis[i + 1][j] && a[i + 1][j] == 1) {
vis[i][j] = 1;
findPathHelper(i + 1, j, a, n, ans, move + 'D', vis);
vis[i][j] = 0;
}
// left
if (j - 1 >= 0 && !vis[i][j - 1] && a[i][j - 1] == 1) {
vis[i][j] = 1;
findPathHelper(i, j - 1, a, n, ans, move + 'L', vis);
vis[i][j] = 0;
}
// right
if (j + 1 < n && !vis[i][j + 1] && a[i][j + 1] == 1) {
vis[i][j] = 1;
findPathHelper(i, j + 1, a, n, ans, move + 'R', vis);
vis[i][j] = 0;
}
// upward
if (i - 1 >= 0 && !vis[i - 1][j] && a[i - 1][j] == 1) {
vis[i][j] = 1;
findPathHelper(i - 1, j, a, n, ans, move + 'U', vis);
vis[i][j] = 0;
}
}
public:
vector < string > findPath(vector < vector < int >> & m, int n) {
vector < string > ans;
vector < vector < int >> vis(n, vector < int > (n, 0));
if (m[0][0] == 1) findPathHelper(0, 0, m, n, ans, "", vis);
return ans;
}
};
int main() {
int n = 4;
vector < vector < int >> m = {{1,0,0,0},{1,1,0,1},{1,1,0,0},{0,1,1,1}};
Solution obj;
vector < string > result = obj.findPath(m, n);
if (result.size() == 0)
cout << -1;
else
for (int i = 0; i < result.size(); i++) cout << result[i] << " ";
cout << endl;
return 0;
}