05 August 2008
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution {
int result;
public int uniquePathsIII(int[][] grid) {
result = 0;
if (grid == null || grid.length == 0 || grid[0].length == 0) {
return result;
}
int m = grid.length;
int n = grid[0].length;
int startx = 0, starty = 0;
int steps = 1;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
startx = i;
starty = j;
continue;
}
if (grid[i][j] == 0) {
steps++;
}
}
}
dfs(grid, startx, starty, steps);
return result;
}
private void dfs(int[][] grid, int px, int py, int steps) {
if (px < 0 || px >= grid.length || py < 0 || py >= grid[0].length || grid[px][py] == -1) {
return;
}
if (grid[px][py] == 2) {
if (steps == 0) {
result++;
}
return;
}
grid[px][py] = -1;
steps--;
dfs(grid, px + 1, py, steps);
dfs(grid, px - 1, py, steps);
dfs(grid, px, py + 1, steps);
dfs(grid, px, py - 1, steps);
grid[px][py] = 0;
}
}