# \[63]\[中等]\[动态规划] 不同路径 II

## 题目描述

[63. 不同路径 II](https://leetcode-cn.com/problems/unique-paths-ii/)

一个机器人位于一个 m x n 网格的左上角 （起始点在下图中标记为“Start” ）。

机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角（在下图中标记为“Finish”）。

现在考虑网格中有障碍物。那么从左上角到右下角将会有多少条不同的路径？

![](/files/-MBj6FK49lGLS6Y7nIOr)

网格中的障碍物和空位置分别用 1 和 0 来表示。

说明：m 和 n 的值均不超过 100。

示例 1:

```
输入:
[
  [0,0,0],
  [0,1,0],
  [0,0,0]
]
输出: 2
解释:
3x3 网格的正中间有一个障碍物。
从左上角到右下角一共有 2 条不同的路径：
1. 向右 -> 向右 -> 向下 -> 向下
2. 向下 -> 向下 -> 向右 -> 向右
```

## 解题思路

到达每一个格子的路径数量, 等于到达左侧格子的路径数量, 加上到达上方格子的路径数量. 因为只有这两个格子能到达此格子, 且到达的方法只有一种.

由于有障碍, 对应格子不可到达, 可以看做得到的路径数量为0.

有意思的是**边际条件**. 在**首列**或者**首行**如果遇到了障碍, 则障碍之后的格子都将不可到达, 初始化时要保持为0.

代码如下:

```python
class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
        height, width = len(obstacleGrid), len(obstacleGrid[0])
        dp = [[0] * width for _ in range(height)]
        for i in range(height):
            if obstacleGrid[i][0] == 1:
                break
            dp[i][0] = 1
        for j in range(width):
            if obstacleGrid[0][j] == 1:
                break
            dp[0][j] = 1

        for i in range(1, height):
            for j in range(1, width):
                if obstacleGrid[i][j] == 0:
                    dp[i][j] = (dp[i - 1][j] if i > 0 else 0) + (dp[i][j - 1] if j > 0 else 0)
        return dp[-1][-1]
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://blessbingo.gitbook.io/garnet/suan-fa/dong-tai-gui-hua/63-bu-tong-lu-jing-ii.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
