---
# System prepended metadata

title: 63. Unique Paths II
tags: [DP]

---

---
title: 63. Unique Paths II
tags: DP
description: share source code.
---

# 63. Unique Paths II

```java=
class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int n = obstacleGrid.length;
        int m = obstacleGrid[0].length;
        int dp[][] = new int [n][m];
            // dp[0][0] = 1;
        
        if(obstacleGrid[0][0] == 1){
            return 0;
        }
        
//         for(int i = 1; i < n; i++ ){
//             if(dp[i - 1][0] == 1 && obstacleGrid[i][0] == 0){
//                 dp[i][0] = 1;
//             } 
//         }
        
//         for(int j = 1; j < m; j++ ){
//             if(dp[0][j - 1] == 1 && obstacleGrid[0][j] == 0){
//                 dp[0][j] = 1;
//             } 
//         }
        
        
        for(int i = 0; i < n; i++ ){
          for(int j = 0; j < m; j++ ){
              if(i == 0 && j == 0){
                  dp[i][j] = 1;
                  continue;
              }
              
              if(obstacleGrid[i][j] == 1){
                  continue;
              }
              
              dp[i][j] =  (i > 0 && obstacleGrid[i - 1][j] == 0 ? dp[i - 1][j] : 0) +
                          (j > 0 && obstacleGrid[i][j - 1] == 0 ? dp[i][j - 1] : 0);
          } 
        }
        System.out.println(Arrays.deepToString(dp));
        
        return dp[n - 1][m - 1];
    }
}
```

