Problem
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 space is marked as 1
and 0
respectively in the grid.
Example 1:
1 | Input: obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]] |
Example 2:
1 | Input: obstacleGrid = [[0,1],[0,0]] |
Constraints:
m == obstacleGrid.length
n == obstacleGrid[i].length
1 <= m, n <= 100
obstacleGrid[i][j]
is0
or1
.
Analysis
比较常规的二维矩阵移动问题,题目要求我们计算的是从左上角出发,到达右下角有多少条不一样的路径。其中矩阵中会有一些不可以行走的点。同时规定了移动的要求是每个格子只能往右边或下边移动,这样看来就是很简单的二维dp了。
首先初始化第一行和第一列,然后从上到下,从左往右遍历即可,这个遍历的顺序和移动的规则要求是保持一致的。如果遇到障碍,则把改点的dp值改为0;否则,则把该点上方和左方的值相加。
Solution
无
Code
1 | class Solution { |
Summary
这道题是很常规的二维dp,刷过很多类似题目的话,这种题目就是秒杀。这道题目的分享到这里,感谢你的支持!