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. class Solution {
  4. public:
  5. int uniquePathsWithObstacles(const vector<vector<int> >& obstacleGrid) {
  6. const int m = obstacleGrid.size();
  7. const int n = obstacleGrid[0].size();
  8. if (obstacleGrid[0][0] || obstacleGrid[m - 1][n - 1]) return 0;
  9. f = vector<vector<int> >(m, vector<int>(n, 0));
  10. f[0][0] = obstacleGrid[0][0] ? 0 : 1;
  11. return dfs(obstacleGrid, m - 1, n - 1);
  12. }
  13. private:
  14. vector<vector<int> > f; // 缓存
  15. // @return 从 (0, 0) 到 (x, y) 的路径总数
  16. int dfs(const vector<vector<int> >& obstacleGrid,
  17. int x, int y) {
  18. if (x < 0 || y < 0) return 0; // 数据非法,终止条件
  19. // (x,y)是障碍
  20. if (obstacleGrid[x][y]) return 0;
  21. if (x == 0 and y == 0) return f[0][0]; // 回到起点,收敛条件
  22. if (f[x][y] > 0) {
  23. return f[x][y];
  24. } else {
  25. return f[x][y] = dfs(obstacleGrid, x - 1, y) +
  26. dfs(obstacleGrid, x, y - 1);
  27. }
  28. }
  29. };

动规

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

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

相关题目

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