-
Notifications
You must be signed in to change notification settings - Fork 0
/
980. Unique Paths III
68 lines (60 loc) · 2.09 KB
/
980. 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
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
class Solution {
public:
void BFS(int i,int j, int& num, int& count, const int &row, const int &col, const int & numWalk, vector<vector<int>>& grid, vector<vector<int>>& visited){
//cout << "i = " << i << ",j = " << j << ",visited =" << visited[i][j] << endl;
if(i < 0 || i >= row || j < 0 || j >= col){
return;
}
if(grid[i][j] == -1){
return;
}
if(grid[i][j] == 2){
if(count == numWalk){
num++;
}
return;
}
if(visited[i][j] == 0){
visited[i][j] = 1;
if(grid[i][j] == 0){
count++;
}
}else{
return;
}
BFS(i+1,j,num,count,row,col,numWalk,grid,visited);
BFS(i-1,j,num,count,row,col,numWalk,grid,visited);
BFS(i,j-1,num,count,row,col,numWalk,grid,visited);
BFS(i,j+1,num,count,row,col,numWalk,grid,visited);
if(grid[i][j] == 0){
count--;
visited[i][j] = 0;
}else{
return;
}
}
int uniquePathsIII(vector<vector<int>>& grid) {
int row = grid.size(), col = grid[0].size(), i = 0, j = 0, count = 0, num = 0, numWalk = 0;
int start_x = 0, start_y = 0, end_x = 0, end_y = 0;
// vector<vector<vector<int>>> path(row,vector<int>(col,vector<int>(4));
vector<vector<int>> visited(row,vector<int>(col));
// cout << visited.size() << endl;
// cout << visited[0].size() << endl;
for(i = 0; i < row; i++){
for(j = 0; j < col; j++){
if(grid[i][j] == 1){
start_x = i;
start_y = j;
}else if(grid[i][j] == 2){
end_x = i;
end_y = j;
}else if(grid[i][j] == 0){
numWalk++;
}
}
}
//visited[start_x][start_y] = 1;
BFS(start_x,start_y,num,count,row,col,numWalk,grid,visited);
return num;
}
};