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 0respectively 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
题目链接:https://leetcode.com/problems/unique-paths-ii/
题目分析:水题,注意头尾
class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int n = obstacleGrid.length;
if (n == 0) {
return 0;
}
int m = obstacleGrid[0].length;
if (obstacleGrid[0][0] == 1 || obstacleGrid[n - 1][m - 1] == 1) {
return 0;
}
int[][] dp = new int[n + 1][m + 1];
dp[1][1] = 1;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
dp[i][j] += obstacleGrid[i - 1][j - 1] == 1 ? 0 : dp[i - 1][j] + dp[i][j - 1];
}
}
return dp[n][m];
}
}

博客讨论了在 m x n 网格中,机器人从左上角到右下角,只能向下或向右移动,且网格中存在障碍物的情况下,有多少条唯一路径的问题。还给出了题目链接,并指出这是一道需注意头尾的简单题。
534

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



