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 3 × 3 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.

备忘录法

在上一题的基础上改一下即可。相比动规,简单得多。

  1. // Unique Paths II
  2. // 深搜 + 缓存,即备忘录法
  3. public class Solution {
  4. public int uniquePathsWithObstacles(int[][] obstacleGrid) {
  5. final int m = obstacleGrid.length;
  6. final int n = obstacleGrid[0].length;
  7. if (obstacleGrid[0][0] != 0 ||
  8. obstacleGrid[m - 1][n - 1] != 0) return 0;
  9. f = new int[m][n];
  10. f[0][0] = obstacleGrid[0][0] != 0 ? 0 : 1;
  11. return dfs(obstacleGrid, m - 1, n - 1);
  12. }
  13. // @return 从 (0, 0) 到 (x, y) 的路径总数
  14. int dfs(int[][] obstacleGrid, int x, int y) {
  15. if (x < 0 || y < 0) return 0; // 数据非法,终止条件
  16. // (x,y)是障碍
  17. if (obstacleGrid[x][y] != 0) return 0;
  18. if (x == 0 && y == 0) return f[0][0]; // 回到起点,收敛条件
  19. if (f[x][y] > 0) {
  20. return f[x][y];
  21. } else {
  22. return f[x][y] = dfs(obstacleGrid, x - 1, y) +
  23. dfs(obstacleGrid, x, y - 1);
  24. }
  25. }
  26. private int[][] f; // 缓存
  27. }

动规

与上一题类似,但要特别注意第一列的障碍。在上一题中,第一列全部是1,但是在这一题中不同,第一列如果某一行有障碍物,那么后面的行全为0。

  1. // Unique Paths II
  2. // 动规,滚动数组
  3. // 时间复杂度O(n^2),空间复杂度O(n)
  4. public class Solution {
  5. public int uniquePathsWithObstacles(int[][] obstacleGrid) {
  6. final int m = obstacleGrid.length;
  7. final int n = obstacleGrid[0].length;
  8. if (obstacleGrid[0][0] != 0 ||
  9. obstacleGrid[m-1][n-1] != 0) return 0;
  10. int[] f = new int[n];
  11. f[0] = obstacleGrid[0][0] != 0 ? 0 : 1;
  12. for (int i = 0; i < m; i++) {
  13. f[0] = f[0] == 0 ? 0 : (obstacleGrid[i][0] != 0 ? 0 : 1);
  14. for (int j = 1; j < n; j++)
  15. f[j] = obstacleGrid[i][j] != 0 ? 0 : (f[j] + f[j - 1]);
  16. }
  17. return f[n - 1];
  18. }
  19. }

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/dfs/unique-paths-ii.html