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
class Solution {
private static final int[][] DIRECTIONS = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

public int uniquePathsIII(int[][] grid) {
int m = grid.length, n = grid[0].length;

int startI = 0, startJ = 0;
int blackCellCount = 0;

for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
startI = i;
startJ = j;
} else if (grid[i][j] == -1) {
blackCellCount++;
}
}
}

int exceptedPathLength = m * n - blackCellCount; // 注意起点和终点也算在路径长度里面

boolean[][] visited = new boolean[m][n];
return dfs(grid, startI, startJ, 0, exceptedPathLength, visited);
}

private int dfs(int[][] grid, int i, int j, int pathLength, int exceptedPathLength, boolean[][] visited) {
int m = grid.length, n = grid[0].length;

if (grid[i][j] == 2) {
// 到达终点
if (pathLength + 1 == exceptedPathLength) {
return 1;
} else {
return 0;
}
}

visited[i][j] = true;
pathLength++;

int pathCount = 0;
for (int[] direction : DIRECTIONS) {
int nextI = i + direction[0], nextJ = j + direction[1];
if (nextI >= 0 && nextI < m && nextJ >= 0 && nextJ < n && grid[nextI][nextJ] != -1 && visited[nextI][nextJ] == false) {
pathCount += dfs(grid, nextI, nextJ, pathLength, exceptedPathLength, visited);
}
}
visited[i][j] = false;
return pathCount;
}
}

References

980. Unique Paths III