题目
Follow up for “Unique Paths”:
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.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[
[0,0,0],
[0,1,0],
[0,0,0]
]
The total number of unique paths is 2.
Note: m and n will be at most 100.
题意
给一个地图矩阵,1表示障碍,0表示可走,
只能向右和向下走, 问0,0到m-1,n-1有多少条不同的路径
分析
dp[i][j]
d
p
[
i
]
[
j
]
表示走到
(i,j)
(
i
,
j
)
上有多少条不同的路径, 因为只能向右向下走, 所以只与左边和上方的一块有关系.
dp[i][j]=obstacleGrid[i][j]==0?dp[i−1][j]+dp[i][j−1]:0
d
p
[
i
]
[
j
]
=
o
b
s
t
a
c
l
e
G
r
i
d
[
i
]
[
j
]
==
0
?
d
p
[
i
−
1
]
[
j
]
+
d
p
[
i
]
[
j
−
1
]
:
0
(i = 0,或j = 0时, 只考虑一个方向)
时间复杂度
O(mn)
O
(
m
n
)
实现
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
if (obstacleGrid.empty()||obstacleGrid[0].empty()) return 0;
int m = obstacleGrid.size(), n = obstacleGrid[0].size();
vector<vector<int>> dp(m, vector<int>(n, 0));
dp[0][0] = 1 - obstacleGrid[0][0];
for (int i = 1;i < m; i++) dp[i][0] = obstacleGrid[i][0] == 0?dp[i-1][0]:0;
for (int j = 1; j < n; j++) dp[0][j] = obstacleGrid[0][j] == 0?dp[0][j-1]:0;
for (int i = 1;i < m; i++) {
for (int j = 1; j < n; j++) {
dp[i][j] = obstacleGrid[i][j] == 0?dp[i-1][j] + dp[i][j-1]:0;
}
}
return dp[m-1][n-1];
}
};