https://leetcode.com/problems/unique-paths-ii/description/
题目
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 0 respectively 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
Solution
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int n = obstacleGrid.size();
if (n == 0) return 0;
int m = obstacleGrid[0].size();
if (m == 0) return 0;
vector<vector<int>> weightedGrid(n, vector<int>(m, 0));
for (int i = n - 1; i >= 0; i--) {
for (int j = m - 1; j >= 0; j--) {
if (obstacleGrid[i][j] == 1)
weightedGrid[i][j] = 0;
else if (i == n - 1 && j == m - 1)
weightedGrid[i][j] = obstacleGrid[i][j] == 0 ? 1 : 0;
else if (i == n - 1)
weightedGrid[i][j] = weightedGrid[i][j+1];
else if (j == m - 1)
weightedGrid[i][j] = weightedGrid[i+1][j];
else
weightedGrid[i][j] = weightedGrid[i+1][j] + weightedGrid[i][j+1];
}
}
return weightedGrid[0][0];
}
};
题解
动态规划的思想嘛,我们从最后一个点开始回溯
- 终点旁边的0点,都拥有1条可以到达终点的路径;
------------> 我们记这些点为S_i
- 对于每个
S_i
旁边的,可以到达S_i
的0点,都可以通过S_i
到达终点,因此他们可达终点的路径个数 ⩾ \geqslant ⩾S_i
的个数;其实就是他可达的每个点的值的和; - 同理,递推到开始点,即可得到
我们可以画张图:
对于全零的地图而言:
* | * | * |
* | * | x |
* | x | 1 |
右下角元素的两个隔壁x继承其值 | ||
* | * | x |
* | y | 1 |
x | 1 | 1 |
同理,y部分继承其右边和下边的值,x继承旁边一个元素的值 | ||
* | x | 1 |
x | 2 | 1 |
1 | 1 | 1 |
同理,两个x继承了1+2=3 | ||
x | 3 | 1 |
3 | 2 | 1 |
1 | 1 | 1 |
最后,x=3+3=6 | ||
6 | 3 | 1 |
3 | 2 | 1 |
1 | 1 | 1 |
当然,这是一个形象化的描述,描述的运算过程和算法实现中的略有不同,但是总体来说是一致的。
分析
- 时间复杂度O(n^2),进行了一个二重循环
- 空间复杂度O(n^2),复制了一整个数组