算法设计与分析-Week17

Russian Doll Envelopes

题目描述

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

解题思路

本题要求从矩阵的左上角到右下角一共有多少种不同的路径,限制只能往右和往下走且中间可能有障碍。
用一个矩阵path,path[i][j]表示到达i行和j列有多少不同的路径,初始化第一行和第一列为1,且如果中间有障碍,后面均为0,例如第一行中间有障碍,障碍后面的路径数均为0,因为向右走无法到达。若不为第一行和第一列,如果第i行第j列不为障碍,则path[i][j] = path[i-1][j] + path[i][j-1];如果第i行第j列为障碍,则path[i][j] = 0。为了节省空间,可用一个一维的数组代替path矩阵。

源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int n = obstacleGrid.size();
int m = obstacleGrid[0].size();
if(obstacleGrid[0][0] == 1 || obstacleGrid[n-1][m-1] == 1) return 0;
vector<long long> path(m, 1);
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(obstacleGrid[i][j] == 1) path[j] = 0;
else if(j == 0) {
path[j] = path[j] == 0 ? 0 : 1;
}
else if(i == 0) {
path[j] = path[j-1] == 0 ? 0 : 1;
}
else path[j] = path[j] + path[j-1];
}
}
return path[m-1];
}
};
0%