题目:
980. Unique Paths III(hard)
解题思路:
回溯+dfs的典型例题。
思路借鉴
代码: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
30public int uniquePathsIII(int[][] grid) {
if(grid == null) return 0;
int startY = 0,startX = 0,stepNum = 1;
for(int i = 0;i < grid.length;i++){
for(int j = 0;j<grid[0].length;j++){
if(grid[i][j] == 1){
startY = i;
startX = j;
continue;
}
if(grid[i][j] == 0) stepNum++;//每个无障碍方格都要通过一次
}
}
return dfs(startX,startY,stepNum,grid);
}
private int dfs(int x,int y,int stepSur,int [][] grid){
if(x < 0 || x >= grid[0].length || y < 0 || y >= grid.length || grid[y][x] == -1) return 0;
if(grid[y][x] == 2) return stepSur == 0 ? 1 : 0;//无障碍方格走完没,走完+1,没走完+0不算
grid[y][x] = -1;//走过的标记设为-1
int res = 0;
res += dfs(x-1,y,stepSur - 1,grid);
res += dfs(x+1,y,stepSur - 1,grid);
res += dfs(x,y-1,stepSur - 1,grid);
res += dfs(x,y+1,stepSur - 1,grid);
grid[y][x] = 0;
return res;
}