题目

63. 不同路径 II

题解



代码:

public class code63 {

    public static int uniquePathsWithObstacles(int[][] obstacleGrid) {
        if (obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0].length == 0) {
            return 0;
        }
        int row = obstacleGrid.length;
        int col = obstacleGrid[0].length;

        int dp[][] = new int[row][col];

        // 第一个数
        if (obstacleGrid[0][0] == 1) {
            dp[0][0] = 0;
        } else if (obstacleGrid[0][0] == 0) {
            dp[0][0] = 1;
        }
        if (dp[0][0] == 0) {
            return 0;
        }

        // 第一列
        for (int i = 1; i < row; i++) {
            if (obstacleGrid[i][0] == 1) {
                dp[i][0] = 0;
            } else if (obstacleGrid[i][0] == 0) {
                dp[i][0] = dp[i - 1][0];
            }
        }

        // 第一行
        for (int j = 1; j < col; j++) {
            if (obstacleGrid[0][j] == 1) {
                dp[0][j] = 0;
            } else if (obstacleGrid[0][j] == 0) {
                dp[0][j] = dp[0][j - 1];
            }
        }

        for (int i = 1; i < row; i++) {
            for (int j = 1; j < col; j++) {
                if (obstacleGrid[i][j] == 1) {
                    dp[i][j] = 0;
                } else if (obstacleGrid[i][j] == 0) {
                    dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
                }

            }
        }
        return dp[row - 1][col - 1];
    }

    public static void main(String[] args) {
        int m[][] = { { 0, 0, 0 }, { 0, 1, 0 }, { 0, 0, 0 } };
        int res = uniquePathsWithObstacles(m);
        System.out.println(res);
    }
}

参考

  1. 不同路径 II——题解一
  2. 自底向上和自顶向下——题解二
  3. 一个格子只能从左边或上边到达,障碍物格子特殊处理