-
Notifications
You must be signed in to change notification settings - Fork 0
/
uniquePathsWithObstacles_63.java
42 lines (39 loc) · 1.46 KB
/
uniquePathsWithObstacles_63.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
/**
* 一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。
机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。
现在考虑网格中有障碍物。那么从左上角到右下角将会有多少条不同的路径?
*/
//dp
class uniquePathsWithObstacles_63 {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
if (obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0][0] == 1) {
return 0;
}
int[][] dp = new int[obstacleGrid.length][obstacleGrid[0].length];
dp[0][0] = 1;
for (int j = 1; j < dp[0].length; j++) {
if (obstacleGrid[0][j] == 0) {
dp[0][j] = 1;
} else {
break;
}
}
for (int i = 1; i < dp.length; i++) {
if (obstacleGrid[i][0] == 0) {
dp[i][0] = 1;
} else {
break;
}
}
for (int i = 1; i < obstacleGrid.length; i++) {
for (int j = 1; j < obstacleGrid[0].length; j++) {
if (obstacleGrid[i][j] == 0) {
dp[i][j] = dp[i][j] + dp[i - 1][j] + dp[i][j - 1];
} else {
continue;
}
}
}
return dp[dp.length - 1][dp[0].length - 1];
}
}