-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUniquePaths3.java
77 lines (63 loc) · 2.04 KB
/
UniquePaths3.java
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
69
70
71
72
73
74
75
76
77
package org.sean.backtracking;
/***
* 980. Unique Paths III
*/
public class UniquePaths3 {
private static final int INT_END = 2;
private static final int INT_OBSTACLE = -1;
private static final int INT_START = 1;
private int pathCnt = 0;
private boolean[][] visited;
private final int[][] directions = new int[][]{
{1, 0}, {0, 1}, {-1, 0}, {0, -1}
};
private int startRow = 0, startCol = 0;
private void traverse(int[][] grid, int row, int col) {
int rowCnt = grid.length;
int colCnt = grid[0].length;
if (grid[row][col] == INT_OBSTACLE) return;
visited[row][col] = true;
if (grid[row][col] == INT_END) {
boolean allVisited = true;
out:
for (int i = 0; i < rowCnt; i++) {
for (int j = 0; j < colCnt; j++) {
if (grid[i][j] != INT_OBSTACLE && !visited[i][j]) {
allVisited = false;
break out;
}
}
}
if (allVisited)
pathCnt++;
return;
}
for (int[] dir : directions) {
int nR = row + dir[0];
int nC = col + dir[1];
if (nR >= 0 && nR < rowCnt && nC >= 0 && nC < colCnt
&& grid[nR][nC] != INT_OBSTACLE && !visited[nR][nC]) {
visited[nR][nC] = true;
traverse(grid, nR, nC);
visited[nR][nC] = false;
}
}
}
public int uniquePathsIII(int[][] grid) {
int rowCnt = grid.length;
int colCnt = grid[0].length;
visited = new boolean[rowCnt][colCnt];
outer:
for (int i = 0; i < rowCnt; i++) {
for (int j = 0; j < colCnt; j++) {
if (grid[i][j] == INT_START) {
startRow = i;
startCol = j;
break outer;
}
}
}
traverse(grid, startRow, startCol);
return pathCnt;
}
}