-
Notifications
You must be signed in to change notification settings - Fork 241
/
Copy pathRatInAMazeProblem1.cpp
117 lines (90 loc) · 2.7 KB
/
RatInAMazeProblem1.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
// https://practice.geeksforgeeks.org/problems/rat-in-a-maze-problem/1
//{ Driver Code Starts
// Initial template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function template for C++
class Solution{
public:
bool safeToGo(vector<vector<int>> &m, int n, int x, int y, vector<vector<int>> visited){
if(x>=0 && x<n && y>=0 && y<n && m[x][y]==1 && visited[x][y]==0)
return true;
else
return false;
}
void solve(vector<vector<int>> &m, int n, int x, int y, vector<vector<int>> visited,
string path, vector<string> &ans){
if(x==n-1 && y==n-1){
ans.push_back(path);
return;
}
visited[x][y]= 1;
//Right
if(safeToGo(m,n,x,y+1,visited)){
path.push_back('R');
solve(m,n,x,y+1,visited,path,ans);
path.pop_back();
}
//Left
if(safeToGo(m,n,x,y-1,visited)){
path.push_back('L');
solve(m,n,x,y-1,visited,path,ans);
path.pop_back();
}
//Down
if(safeToGo(m,n,x+1,y,visited)){
path.push_back('D');
solve(m,n,x+1,y,visited,path,ans);
path.pop_back();
}
//Up
if(safeToGo(m,n,x-1,y,visited)){
path.push_back('U');
solve(m,n,x-1,y,visited,path,ans);
path.pop_back();
}
visited[x][y]=0;
}
vector<string> findPath(vector<vector<int>> &m, int n) {
vector<vector<int>> visited= m;
vector<string> ans;
string path="";
if(m[0][0]==0)
return ans;
int srcX=0, srcY=0;
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
visited[i][j]=0;
}
}
solve(m, n, srcX, srcY, visited, path, ans);
sort(ans.begin(), ans.end());
return ans;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<vector<int>> m(n, vector<int> (n,0));
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> m[i][j];
}
}
Solution obj;
vector<string> result = obj.findPath(m, n);
sort(result.begin(), result.end());
if (result.size() == 0)
cout << -1;
else
for (int i = 0; i < result.size(); i++) cout << result[i] << " ";
cout << endl;
}
return 0;
}
// } Driver Code Ends