题目如下:
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? Example: 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
63. Unique Paths II
这道题是在62. Unique Paths(解法见[LeetCode每日一题]62. Unique Paths)的基础上修改的,添加了障碍物,设状态空间为dp[][],状态转移方程为
dp[i][j] = dp[i-1][j] + dp[i][j-1], obstacleGrid[i][j]==0 dp[i][j] = 0, obstacleGrid[i][j]==1
实现代码如下:
class Solution { public int uniquePathsWithObstacles(int[][] obstacleGrid) { if (obstacleGrid == null || obstacleGrid[0] == null) { return 0; } int x = obstacleGrid.length; int y = obstacleGrid[0].length; int[][] dp = new int[x][y]; dp[0][0] = obstacleGrid[0][0] == 0 ? 1 : 0; for (int i = 1; i < x; i++) { dp[i][0] = obstacleGrid[i][0] == 1 ? 0 : dp[i - 1][0]; } for (int j = 1; j < y; j++) { dp[0][j] = obstacleGrid[0][j] == 1 ? 0 : dp[0][j - 1]; } for (int i = 1; i < x; i++) { for (int j = 1; j < y; j++) { dp[i][j] = obstacleGrid[i][j] == 0 ? dp[i - 1][j] + dp[i][j - 1] : 0; } } return dp[x - 1][y - 1]; } }
- 本文固定链接: https://weiguangli.com/archives/449
- 转载请注明: lwg0452 于 Weiguang的博客 发表
捐 赠如果您觉得这篇文章有用处,请支持作者!鼓励作者写出更好更多的文章!