不同路径Ⅱ

LeetCode每日一题,63.Unique Paths II

先看题目描述

大意就是给定网格中的空位和障碍的位置,让我们返回从左上走到右下一共有几种走法

算法和思路

使用动态规划就可以解决

  • dp[i][j] 表示走到 obstaclGrid[i][j] 共有几种走法

  • 状态转移方程:

    • 若 obstacleGrid[i][0] = 0,dp[i][0] = dp[i - 1][0],否则,dp[i][0] = 0
    • 若 obstacleGrid[0][i] = 0,dp[0][i] = dp[0][i - 1],否则,dp[0][i] = 0
    • 当 i, j 均大于等于 1 时
      • 若 obstacleGrid[i][j] = 0,dp[i][j] = dp[i - 1][j] + dp[i][j - 1],否则 dp[i][j] = 0
  • 初始化时,若 obstacleGrid[i][j] = 0,dp[0][0] = 1,否则直接返回 0

算法源码

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
class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m = obstacleGrid.length;
if (m == 0) return 0;
int n = obstacleGrid[0].length;
if (n == 0) return 0;
int[][] dp = new int[m][n];
if (obstacleGrid[0][0] == 1) return 0;
dp[0][0] = 1;
for (int i = 1; i < m; i++) {
if (obstacleGrid[i][0] == 0) dp[i][0] = dp[i - 1][0];
else dp[i][0] = 0;

}
for (int i = 1; i < n; i++) {
if (obstacleGrid[0][i] == 0) dp[0][i] = dp[0][i - 1];
else dp[0][i] = 0;
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (obstacleGrid[i][j] == 0) dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
else dp[i][j] = 0;
}
}
return dp[m - 1][n - 1];
}
}