AlgoMaster Logo

Unique Paths II

grid=[[0,0,0],[0,1,0],[0,0,0]]
1public int uniquePathsWithObstacles(int[][] obstacleGrid) {
2    int m = obstacleGrid.length;
3    int n = obstacleGrid[0].length;
4    int[][] dp = new int[m][n];
5
6    // Initialize the first cell
7    dp[0][0] = obstacleGrid[0][0] == 0 ? 1 : 0;
8
9    // Fill the first column
10    for (int i = 1; i < m; i++) {
11        dp[i][0] = obstacleGrid[i][0] == 0 ? dp[i-1][0] : 0;
12    }
13
14    // Fill the first row
15    for (int j = 1; j < n; j++) {
16        dp[0][j] = obstacleGrid[0][j] == 0 ? dp[0][j-1] : 0;
17    }
18
19    // Fill the rest of the dp table
20    for (int i = 1; i < m; i++) {
21        for (int j = 1; j < n; j++) {
22            if (obstacleGrid[i][j] == 0) {
23                dp[i][j] = dp[i-1][j] + dp[i][j-1];
24            }
25        }
26    }
27
28    return dp[m-1][n-1];
29}
0 / 20
X000000000012012Grid012012dp