题目
一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为 “Start” )。
机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为 “Finish”)。
现在考虑网格中有障碍物。那么从左上角到右下角将会有多少条不同的路径?
网格中的障碍物和空位置分别用 1 和 0 来表示。
示例 1:
输入:obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
输出:2
解释:3x3 网格的正中间有一个障碍物。
从左上角到右下角一共有 2 条不同的路径:
- 向右 -> 向右 -> 向下 -> 向下
- 向下 -> 向下 -> 向右 -> 向右
示例 2:
输入:obstacleGrid = [[0,1],[0,0]]
输出:1
解题思路
本题和leetcode 62不同路径的区别在于网格中可能存在障碍物,方法仍然是动态规划,递推公式为dp[i][j]=dp[i-1][0]+dp[0][j-1],但能递推的条件是当前网格没有障碍物。本题初始化与leetcode 62差异最大,如果首尾节点存在障碍物,则无法达到终点,直接return 0. 第一行和第一列初始化时,也要判断当前位置是否存在障碍物,如果不存在,则初始化为1,否则默认为0.
代码实现
class Solution {
public:int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {int m = obstacleGrid.size();int n = obstacleGrid[0].size();// If the starting position or the ending position is blocked, there are no possible pathsif (obstacleGrid[0][0] == 1 || obstacleGrid[m-1][n-1] == 1) {return 0;}vector<vector<long long>> dp(m, vector<long long>(n, 0));// Initialize the first row and first columndp[0][0] = 1; // Starting positionfor (int i = 1; i < m; i++) {if (obstacleGrid[i][0] != 1) {dp[i][0] = dp[i-1][0];}}for (int j = 1; j < n; j++) {if (obstacleGrid[0][j] != 1) {dp[0][j] = dp[0][j-1];}}// Calculate the number of unique paths for each positionfor (int i = 1; i < m; i++) {for (int j = 1; j < n; j++) {if (obstacleGrid[i][j] != 1) {dp[i][j] = dp[i-1][j] + dp[i][j-1];}}}return dp[m-1][n-1];}
};