forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUnique Paths III.java
40 lines (40 loc) · 1.12 KB
/
Unique Paths III.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
class Solution {
int walk = 0;
public int uniquePathsIII(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 0) {
walk++;
}
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
return ways(grid, i, j, m, n, 0);
}
}
}
return 0;
}
public int ways(int[][] grid, int cr, int cc, int m, int n, int count) {
if (cr < 0 || cr == m || cc < 0 || cc == n || grid[cr][cc] == -1) {
return 0;
}
if (grid[cr][cc] == 2) {
if (count - 1 == walk) return 1;
return 0;
}
grid[cr][cc] = -1;
int ans = 0;
int[] r = {0, 1, 0, -1};
int[] c = {1, 0, -1, 0};
for (int i = 0; i < 4; i++) {
ans += ways(grid, cr + r[i], cc + c[i], m, n, count + 1);
}
grid[cr][cc] = 0;
return ans;
}
}