【一次過】【座標型】Lintcode 115. 不同的路徑 II
阿新 • • 發佈:2019-01-30
"不同的路徑" 的跟進問題:
現在考慮網格中有障礙物,那樣將會有多少條不同的路徑?
網格中的障礙和空位置分別用 1 和 0 來表示。
樣例
如下所示在3x3的網格中有一個障礙物:
[
[0,0,0],
[0,1,0],
[0,0,0]
]
一共有2條不同的路徑從左上角到右下角。
注意事項
m 和 n 均不超過100
解題思路:
和Lintcode 114. 不同的路徑類似。設dp[i][j]為機器人有多少種方式從左上角走到[i][j]。
public class Solution { /** * @param obstacleGrid: A list of lists of integers * @return: An integer */ public int uniquePathsWithObstacles(int[][] obstacleGrid) { // write your code here if(obstacleGrid==null || obstacleGrid.length==0 ||obstacleGrid[0].length==0 || obstacleGrid[0][0]==1) return 0; int m = obstacleGrid.length; int n = obstacleGrid[0].length; int[][] dp = new int[m][n]; //初始條件 dp[0][0] = 1; //邊界條件 for(int i=1 ; i<m ; i++){ if(obstacleGrid[i][0] == 1) dp[i][0] = 0; else dp[i][0] = dp[i-1][0]; } for(int j=1 ; j<n ; j++){ if(obstacleGrid[0][j] == 1) dp[0][j] = 0; else dp[0][j] = dp[0][j-1]; } //狀態方程 for(int i=1 ; i<m ; i++){ for(int j=1 ; j<n ; j++){ if(obstacleGrid[i][j] == 1) dp[i][j] = 0; else dp[i][j] = dp[i-1][j] + dp[i][j-1]; } } return dp[m-1][n-1]; } }