leetcode63:Unique Paths II
阿新 • • 發佈:2018-12-11
思路:在Unique Paths上多加了一些障礙點,做法同Unique Paths類似,只是在初始化和計算dp[i][j]的時候,需要判斷i行j列是否為障礙點,如果是,表示路徑不通,置為0,否則正常計算。dp[i][j]=dp[i - 1][j] + dp[i][j - 1]。
程式碼:
public class UniquePathsII63 { public static void main(String[] args) { int[][] num = { { 0, 0, 0 }, { 0, 1, 0 }, { 0, 0, 0 } }; System.out.println(uniquePathsWithObstacles(num)); } public static int uniquePathsWithObstacles(int[][] obstacleGrid) { int[][] dp = new int[obstacleGrid.length][obstacleGrid[0].length]; /****** 初始化的地方需要注意 *********/ for (int i = 0; i < obstacleGrid[0].length; i++) if (obstacleGrid[0][i] != 1) dp[0][i] = 1; else break; for (int i = 0; i < obstacleGrid.length; i++) if (obstacleGrid[i][0] != 1) dp[i][0] = 1; else break; /****** 初始化完成 ***************/ for (int i = 1; i < obstacleGrid.length; i++) { for (int j = 1; j < obstacleGrid[0].length; j++) { if (obstacleGrid[i][j] != 1) dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; } } return dp[obstacleGrid.length - 1][obstacleGrid[0].length - 1]; } }
輸出: