-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrats_in_maze2.cpp
59 lines (52 loc) · 1.43 KB
/
rats_in_maze2.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
#include <bits/stdc++.h>
using namespace std;
class Solution {
void solve(int i, int j, vector < vector < int >> & a, int n, vector < string > & ans, string move,
vector < vector < int >> & vis, int di[], int dj[]) {
if (i == n - 1 && j == n - 1) {
ans.push_back(move);
return;
}
string dir = "DLRU";
for (int ind = 0; ind < 4; ind++) {
int nexti = i + di[ind];
int nextj = j + dj[ind];
if (nexti >= 0 && nextj >= 0 && nexti < n && nextj < n && !vis[nexti][nextj] && a[nexti][nextj] == 1) {
vis[i][j] = 1;
solve(nexti, nextj, a, n, ans, move + dir[ind], vis, di, dj);
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));
int di[] = {
+1,
0,
0,
-1
};
int dj[] = {
0,
-1,
1,
0
};
if (m[0][0] == 1) solve(0, 0, m, n, ans, "", vis, di, dj);
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;
}