[LeetCode] 63. 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.
[ [0,0,0], [0,1,0], [0,0,0] ]
The total number of unique paths is
2
.
Note: m and n will be at most 100.
Thought process:
Sub-problem, initialization, and answer are the same as "62. Unique Paths".
Formula: f[i][j] = f[i - 1][j] + f[i][j - 1] if grid[i][j] == 0; 0 otherwise.
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | public class Solution { public int uniquePathsWithObstacles(int[][] obstacleGrid) { int height = obstacleGrid.length; if (height == 0) { return 0; } int width = obstacleGrid[0].length; if (width == 0) { return 0; } int[][] f = new int[height][width]; for (int i = 0; i < height; i++) { if (obstacleGrid[i][0] == 1) { break; } f[i][0] = 1; } for (int i = 0; i < width; i++) { if (obstacleGrid[0][i] == 1) { break; } f[0][i] = 1; } for (int i = 1; i < height; i++) { for (int j = 1; j < width; j++) { if (obstacleGrid[i][j] == 1) { f[i][j] = 0; } else { f[i][j] = f[i - 1][j] + f[i][j - 1]; } } } return f[height - 1][width - 1]; } } |
Time complexity: O(mn).
Count and also print all unique paths:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | class Solution { public int uniquePathsWithObstacles(int[][] obstacleGrid) { int m = obstacleGrid.length; if (m == 0) { return 0; } int n = obstacleGrid[0].length; List<String> paths = new ArrayList<>(); int result = uniquePathsWithObstacles(obstacleGrid, m - 1, n - 1, "", paths); System.out.println(paths); return result; } private int uniquePathsWithObstacles(int[][] obstacleGrid, int row, int col, String path, List<String> paths) { if (obstacleGrid[row][col] == 1) { return 0; } if (row == 0 && col == 0) { paths.add(path); return 1; } if (row == 0) { return uniquePathsWithObstacles(obstacleGrid, row, col - 1, "r" + path, paths); } if (col == 0) { return uniquePathsWithObstacles(obstacleGrid, row - 1, col, "b" + path, paths); } return uniquePathsWithObstacles(obstacleGrid, row - 1, col, "b" + path, paths) + uniquePathsWithObstacles(obstacleGrid, row, col - 1, "r" + path, paths); } } |
Time complexity: O(2^(m + n)).
Space complexity: O(2^(m + n)).
Comments
Post a Comment