Follow up for "Unique Paths":
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.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[
[0,0,0],
[0,1,0],
[0,0,0]
]
The total number of unique paths is 2.
Note: m and n will be at most 100.
这道题目是[url=http://kickcode.iteye.com/blog/2275198]Unique Paths[/url]的变形题目,用1代表障碍物,有障碍物的地方就是死路,同样采用动态规划的思想,只是多了一些限定条件,当为1时,我们就把当前点的值设定为0;当为0的时候,如果此时(i = 0或者j = 0)这时当前点的值等于它前面的点的值(相当于初始化的过程),如果此时(i > 0并且j > 0),动态转移方程为dp[i][j] = dp[i - 1][j] + dp[i][j - 1],(i >= 1, j >= 1)。代码如下:
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.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[
[0,0,0],
[0,1,0],
[0,0,0]
]
The total number of unique paths is 2.
Note: m and n will be at most 100.
这道题目是[url=http://kickcode.iteye.com/blog/2275198]Unique Paths[/url]的变形题目,用1代表障碍物,有障碍物的地方就是死路,同样采用动态规划的思想,只是多了一些限定条件,当为1时,我们就把当前点的值设定为0;当为0的时候,如果此时(i = 0或者j = 0)这时当前点的值等于它前面的点的值(相当于初始化的过程),如果此时(i > 0并且j > 0),动态转移方程为dp[i][j] = dp[i - 1][j] + dp[i][j - 1],(i >= 1, j >= 1)。代码如下:
public class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
if(obstacleGrid == null || obstacleGrid.length == 0) return 0;
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++) {
if(obstacleGrid[i][j] == 1) obstacleGrid[i][j] = 0;
else if (i == 0 && j == 0) obstacleGrid[0][0] = 1;
else if(i == 0) obstacleGrid[0][j] = obstacleGrid[0][j - 1];
else if(j == 0) obstacleGrid[i][0] = obstacleGrid[i - 1][0];
else obstacleGrid[i][j] = obstacleGrid[i - 1][j] + obstacleGrid[i][j - 1];
}
return obstacleGrid[m - 1][n - 1];
}
}
本文介绍了一种使用动态规划解决网格中带有障碍物的唯一路径数量的问题。在3x3的网格中,若中间存在一个障碍物,则总共有2条唯一的路径可以到达终点。文章详细解释了动态规划的方法,并给出了实现的代码。
1155

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



