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.
<Solution>Unique Path 的衍生題
這次增加的條件是,有些位置是無法到達的
那思路還是一樣,用 dynamic programming 的方式去解
解題想法如下
- 從位置 (0,0) 出發,如果遇到障礙物,就把該位置可到達步數清為0
- 如果沒遇到障礙物,就用 dp[i][j] = dp[i-1][j] + dp[i][j-1] 的概念去解
c++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { | |
if(obstacleGrid.size() == 1 && obstacleGrid[0].size() == 1) { | |
return (obstacleGrid[0][0] == 1) ? 0 : 1; | |
} | |
const int m = obstacleGrid.size(), n = obstacleGrid[0].size(); | |
vector<int> dp(n, 0); | |
dp[0] = 1; | |
for(int r = 0; r < m; r++) { | |
for(int c = 0; c < n; c++) { | |
if(obstacleGrid[r][c] == 1) { | |
//> obstacle | |
dp[c] = 0; | |
} | |
else if(c > 0) { | |
dp[c] += dp[c-1]; | |
} | |
} | |
} | |
return dp[n-1]; | |
} | |
}; |
kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
fun uniquePathsWithObstacles(obstacleGrid: Array<IntArray>): Int { | |
return if(obstacleGrid[0][0] == 1) { | |
0 | |
} else { | |
val m = obstacleGrid.size | |
val n = obstacleGrid[0].size | |
val dp = Array(m) { IntArray(n) {0} } | |
dp[0][0] = 1 | |
for(c in 1 until n) { | |
dp[0][c] = if(obstacleGrid[0][c] == 1) 0 else dp[0][c-1] | |
} | |
for(r in 1 until m) { | |
dp[r][0] = if(obstacleGrid[r][0] == 1) 0 else dp[r-1][0] | |
} | |
for(r in 1 until m) { | |
for (c in 1 until n) { | |
dp[r][c] = if(obstacleGrid[r][c] == 1) { | |
0 | |
} else { | |
dp[r-1][c] + dp[r][c-1] | |
} | |
} | |
} | |
dp.last().last() | |
} | |
} | |
} |
沒有留言:
張貼留言