不同路径 II (Unique Paths II)

 

思路:

// @Title: 不同路径 II (Unique Paths II)
// @Author: qisiii
// @Date: 2024-09-22 23:40:00
// @Runtime: 0 ms
// @Memory: 40.6 MB
// @comment: 
// @flag: 
class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int m = obstacleGrid.length, n = obstacleGrid[0].length;
        int[][] dp = new int[m][n];
        boolean row = false, column = false;
        for (int j = 0; j < n; j++) {
            if (obstacleGrid[0][j] == 1) {
                row = true;
            }
            if (row) {
                dp[0][j] = 0;
            } else {
                dp[0][j] = 1;
            }
        }
        for (int j = 0; j < m; j++) {
            if (obstacleGrid[j][0] == 1) {
                column = true;
            }
            if (column) {
                dp[j][0] = 0;
            } else {
                dp[j][0] = 1;
            }
        }
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                if (obstacleGrid[i][j] == 1) {
                    dp[i][j] = 0;
                    continue;
                }
                dp[i][j] = dp[i][j - 1] + dp[i - 1][j];
            }
        }
        return dp[m - 1][n - 1];
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18