forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnique Paths III.java
More file actions
66 lines (55 loc) · 2.16 KB
/
Unique Paths III.java
File metadata and controls
66 lines (55 loc) · 2.16 KB
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
class Solution {
int numOfPaths;
public int uniquePathsIII(int[][] grid) {
numOfPaths = 0;
if (grid.length == 0 || grid[0].length == 0) {
return numOfPaths;
}
int startX = -1;
int startY = -1;
int emptyObstacleCount = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] == 1) {
startX = i;
startY = j;
} else if (grid[i][j] == 0) {
emptyObstacleCount++;
}
}
}
dfsHelper(grid, startX, startY, emptyObstacleCount, 0, new boolean[grid.length][grid[0].length]);
return numOfPaths;
}
private void dfsHelper(int[][] grid,
int startX,
int startY,
int emptyObstacleCount,
int currObstacleCount,
boolean[][] visited) {
if (startX < 0 ||
startX >= grid.length ||
startY < 0 ||
startY >= grid[0].length ||
visited[startX][startY] ||
grid[startX][startY] == -1) {
return;
}
if (grid[startX][startY] == 2) {
if (currObstacleCount == emptyObstacleCount) {
numOfPaths++;
}
return;
}
visited[startX][startY] = true;
dfsHelper(grid, startX + 1, startY, emptyObstacleCount,
grid[startX][startY] == 0 ? currObstacleCount + 1 : currObstacleCount, visited);
dfsHelper(grid, startX - 1, startY, emptyObstacleCount,
grid[startX][startY] == 0 ? currObstacleCount + 1 : currObstacleCount, visited);
dfsHelper(grid, startX, startY + 1, emptyObstacleCount,
grid[startX][startY] == 0 ? currObstacleCount + 1 : currObstacleCount, visited);
dfsHelper(grid, startX, startY - 1, emptyObstacleCount,
grid[startX][startY] == 0 ? currObstacleCount + 1 : currObstacleCount, visited);
visited[startX][startY] = false;
}
}