Repository navigation
Expand file tree
/
Copy pathLecture40.cpp
More file actions
105 lines (84 loc) · 2.48 KB
/
Copy pathLecture40.cpp
File metadata and controls
105 lines (84 loc) · 2.48 KB
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
// practice need
#include<iostream>
#include<vector>
#include<string>
using namespace std;
class Solution{
private:
bool isSafe(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,string path,vector<string>& ans,vector<vector<int>> visited){
//base case --->reached at destination
if(x==n-1 && y==n-1){
ans.push_back(path);
return ;
}
visited[x][y]=1;
//down
int newx = x+1;
int newy = y;
if(isSafe(m,n,newx,newy,visited)){
path.push_back('D');
solve(m,n,newx,newy,path,ans,visited);
path.pop_back();
}
//Left
newx = x;
newy = y-1;
if(isSafe(m,n,newx,newy,visited)){
path.push_back('L');
solve(m,n,newx,newy,path,ans,visited);
path.pop_back();
}
//Right
newx = x;
newy = y+1;
if(isSafe(m,n,newx,newy,visited)){
path.push_back('R');
solve(m,n,newx,newy,path,ans,visited);
path.pop_back();
}
//Up
newx = x-1;
newy = y;
if(isSafe(m,n,newx,newy,visited)){
path.push_back('U');
solve(m,n,newx,newy,path,ans,visited);
path.pop_back();
}
visited[x][y]=0; //backtracking
}
public:
vector<string> findPath(vector<vector<int>> &m, int n) {
// 0---> not allowed
// 1--->allowed
vector<string> ans;
//not allowed at starting coordinate
if(m[0][0]==0){
return ans;
}
//starting coordinate
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,srcx,srcy,path,ans,visited);
// sort(ans.begin(),ans.end());
return ans;
}
};
int main(){
return ;
}
// lecture 41 :- pending questions