-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUnique Paths III
35 lines (35 loc) · 960 Bytes
/
Unique Paths III
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
class Solution {
public:
int dfs(int i,int j,vector<vector<int>> grid,int zero){
if(i<0 || j<0 || i>=grid.size() || j>=grid[0].size() || grid[i][j]==-1){
return 0;
}
if(grid[i][j]==2){
return zero==-1?1:0;
}
grid[i][j]=-1;
zero--;
int totalpaths=dfs(i+1,j,grid,zero)+dfs(i-1,j,grid,zero)+dfs(i,j+1,grid,zero)+dfs(i,j-1,grid,zero);
grid[i][j]=0;
zero++;
return totalpaths;
}
int uniquePathsIII(vector<vector<int>>& grid) {
int n=grid.size();
int m=grid[0].size();
int count=0;
int sx=0;
int sy=0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(grid[i][j]==0){
count++;
}else if(grid[i][j]==1){
sx=i;
sy=j;
}
}
}
return dfs(sx,sy,grid,count);
}
};