Unique Paths II (M)
A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).
Now consider if some obstacles are added to the grids. How many unique paths would there be?

An obstacle and empty space is marked as 1 and 0 respectively in the grid.
Note: m and n will be at most 100.
Example 1:
Input:
[
[0,0,0],
[0,1,0],
[0,0,0]
]
Output: 2
Explanation:
There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right
题意
在矩形中找到一条路径,起点为左上顶点,终点为右下顶点,路径中只能向右或向下走,且矩形中存在不能通过的障碍点,要求统计不同路径的个数。
思路
与 62. Unique Paths 方法一致,只是多了障碍点不好用组合数解决问题。使用动态规划,并用滚动数组进行优化。
代码实现 - 动态规划
class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int n = obstacleGrid.length, m = obstacleGrid[0].length;
int[][] dp = new int[n][m];
dp[0][0] = obstacleGrid[0][0] == 1 ? 0 : 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (i != 0 || j != 0) {
dp[i][j] = obstacleGrid[i][j] == 1 ? 0 :
((i == 0 ? 0 : dp[i - 1][j]) + (j == 0 ? 0 : dp[i][j - 1]));
}
}
}
return dp[n - 1][m - 1];
}
}
代码实现 - 滚动数组优化
class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int n = obstacleGrid.length, m = obstacleGrid[0].length;
int[] dp = new int[m];
dp[0] = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
dp[j] = obstacleGrid[i][j] == 1 ? 0 : j > 0 ? dp[j - 1] + dp[j] : dp[j];
}
}
return dp[m - 1];
}
}
本文探讨了在包含障碍物的网格中寻找从左上角到右下角的不同路径数量的问题。介绍了如何应用动态规划解决该问题,包括标准动态规划和滚动数组优化两种方法。
1166

被折叠的 条评论
为什么被折叠?



