[LeetCode]63 不同的路徑總數之二
阿新 • • 發佈:2018-12-26
Unique Paths II(不同的路徑總數之二)
【難度:Medium】
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.
LeetCode 62題的擴充套件,為機器人增加了障礙物,0表示空地,1表示障礙,同樣求從左上角到右下角不同的走法總數。
解題思路
在62題的基礎上解決這個問題,但需要考慮的是,機器人不能簡單地向下或向右走,要判斷是否有障礙物,因此左邊界和上邊界的初始化也要根據上一個點的狀態來設定,同樣使用動態規劃來完成。
c++程式碼如下:
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
if (obstacleGrid.empty())
return 0;
//入口有障礙的話,直接返回
if (obstacleGrid[0][0] == 1)
return 0;
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
vector<vector<int>> path(m,vector<int>(n,0));
//入口點走法只有1種。
path[0][0] = 1;
for (int i = 1; i < m; i++) {
//左邊界,如果上一點可行並且當前點沒有障礙物,那麼該點可走
if (path[i-1][0] != 0 && obstacleGrid[i][0] != 1)
path[i][0] = 1;
}
for (int i = 1; i < n; i++) {
//上邊界與左邊界情況同理
if (path[0][i-1] != 0 && obstacleGrid[0][i] != 1)
path[0][i] = 1;
}
for (int i = 1; i < m; i++)
for (int j = 1; j < n; j++)
//動態規劃,當前點無障礙物則與62題處理方法一致
if (obstacleGrid[i][j] != 1)
path[i][j] = path[i-1][j]+path[i][j-1];
return path[m-1][n-1];
}
};