- Unique Paths II
Unique Paths II
Follow up for “Unique Paths”:
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1 and 0 respectively in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
1. [
2. [0,0,0],
3. [0,1,0],
4. [0,0,0]
5. ]
The total number of unique paths is 2.
Note: m and n will be at most 100.
Solution:
1. public class Solution {
2. public int uniquePathsWithObstacles(int[][] obstacleGrid) {
3. int m = obstacleGrid.length;
4. int n = obstacleGrid[0].length;
5. int[][] dp = new int[m][n];
6. 7. // first row
8. for (int j = 0; j < n; j++) {
9. if (obstacleGrid[0][j] == 1) {
10. break;
11. }
12. dp[0][j] = 1;
13. }
14. 15. // first col
16. for (int i = 0; i < m; i++) {
17. if (obstacleGrid[i][0] == 1) {
18. break;
19. }
20. dp[i][0] = 1;
21. }
22. 23. // others
24. for (int i = 1; i < m; i++) {
25. for (int j = 1; j < n; j++) {
26. if (obstacleGrid[i][j] == 0) {
27. dp[i][j] = dp[i-1][j] + dp[i][j-1];
28. }
29. }
30. }
31. 32. return dp[m-1][n-1];
33. }
34. }
