題目
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.
分析
和第62題基本一樣,不同的是在初始化時(shí)要將障礙處的路徑數(shù)置為0,且在推導(dǎo)的時(shí)候跳過(guò)這些位置。
而且也要推導(dǎo)最后兩行。
實(shí)現(xià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();
int dp[m][n];
dp[m-1][n-1] = 1;
for(int i=0; i<m; i++)
for(int j=0; j<n; j++)
if(obstacleGrid[i][j])
dp[i][j] = 0;
for(int i=m-2; i>=0; i--)
if(!obstacleGrid[i][n-1]) dp[i][n-1] = dp[i+1][n-1];
for(int i=n-2; i>=0; i--)
if(!obstacleGrid[m-1][i]) dp[m-1][i] = dp[m-1][i+1];
for(int i=m-2; i>=0; i--)
for(int j=n-2; j>=0; j--)
if(!obstacleGrid[i][j])
dp[i][j] = dp[i+1][j] + dp[i][j+1];
return dp[0][0];
}
};
思考
做這種題的時(shí)候要非常注意,條件增加時(shí)變化了的情況。如果繼續(xù)沿用之前的那種初始化最后一行和最后一列為1的情況就會(huì)出現(xiàn)問題,改成由后一個(gè)推導(dǎo)才可。