-
Notifications
You must be signed in to change notification settings - Fork 0
/
lec40_rec10_ratinamaze.cpp
152 lines (116 loc) · 2.86 KB
/
lec40_rec10_ratinamaze.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
//{ Driver Code Starts
// Initial template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function template for C++
class Solution{
private:
bool isSafe(int x,int y,int n,vector<vector<int>> visited, vector<vector<int>> m)
{
if((x>=0&&x<n)&&(y>=0&&y<n)&&(visited[x][y]==0)&&(m[x][y]==1))
{
return 0;
}
else
return 1;
}
void solve(vector<vector<int>> m,int n, vector <string> &ans,int x, int y,vector<vector<int>> visited, string path)
{
//base case // reached END
if(x==n-1 && y==n-1){
ans.push_back(path);
return ;
}
visited[x][y]=1;
//4 choices= D L R U
//down
int newx= x+1;
int newy=y;
if(isSafe(newx,newy,n,visited,m))
{
path.push_back('D');
solve(m,n,ans,newx,newy,visited,path);
path.pop_back();
}
//left
newx= x;
newy=y-1;
if(isSafe(newx,newy,n,visited,m))
{
path.push_back('L');
solve(m,n,ans,newx,newy,visited,path);
path.pop_back();
}
//right
newx= x;
newy=y+1;
if(isSafe(newx,newy,n,visited,m))
{
path.push_back('L');
solve(m,n,ans,newx,newy,visited,path);
path.pop_back();
}
//up
newx= x-1;
newy=y;
if(isSafe(newx,newy,n,visited,m))
{
path.push_back('L');
solve(m,n,ans,newx,newy,visited,path);
path.pop_back();
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
visited[i][j]=0;
}
}
}
public:
vector<string> findPath(vector<vector<int>> &m, int n) {
vector<string> ans;
if(m[0][0]==0)
return ans;
int srcx=0;
int srcy=0;
vector<vector<int>> visited = m;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
visited[i][j]=0;
}
}
string path = "";
solve(m,n,ans,srcx,srcy,visited,path);
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