Unique Paths II

  • tags: [DP_Matrix]

Question

  1. Follow up for "Unique Paths":
  2. Now consider if some obstacles are added to the grids.
  3. How many unique paths would there be?
  4. An obstacle and empty space is marked as 1 and 0 respectively in the grid.
  5. Note
  6. m and n will be at most 100.
  7. Example
  8. For example,
  9. There is one obstacle in the middle of a 3x3 grid as illustrated below.
  10. [
  11. [0,0,0],
  12. [0,1,0],
  13. [0,0,0]
  14. ]
  15. The total number of unique paths is 2.

题解

在上题的基础上加了obstacal这么一个限制条件,那么也就意味着凡是遇到障碍点,其路径数马上变为0,需要注意的是初始化环节和上题有较大不同。首先来看看错误的初始化实现。

C++ initialization error

  1. class Solution {
  2. public:
  3. /**
  4. * @param obstacleGrid: A list of lists of integers
  5. * @return: An integer
  6. */
  7. int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
  8. if(obstacleGrid.empty() || obstacleGrid[0].empty()) {
  9. return 0;
  10. }
  11. const int M = obstacleGrid.size();
  12. const int N = obstacleGrid[0].size();
  13. vector<vector<int> > ret(M, vector<int>(N, 0));
  14. for (int i = 0; i != M; ++i) {
  15. if (0 == obstacleGrid[i][0]) {
  16. ret[i][0] = 1;
  17. }
  18. }
  19. for (int i = 0; i != N; ++i) {
  20. if (0 == obstacleGrid[0][i]) {
  21. ret[0][i] = 1;
  22. }
  23. }
  24. for (int i = 1; i != M; ++i) {
  25. for (int j = 1; j != N; ++j) {
  26. if (obstacleGrid[i][j]) {
  27. ret[i][j] = 0;
  28. } else {
  29. ret[i][j] = ret[i -1][j] + ret[i][j - 1];
  30. }
  31. }
  32. }
  33. return ret[M - 1][N - 1];
  34. }
  35. };

源码分析

错误之处在于初始化第0行和第0列时,未考虑到若第0行/列有一个坐标出现障碍物,则当前行/列后的元素路径数均为0!

C++

  1. class Solution {
  2. public:
  3. /**
  4. * @param obstacleGrid: A list of lists of integers
  5. * @return: An integer
  6. */
  7. int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
  8. if(obstacleGrid.empty() || obstacleGrid[0].empty()) {
  9. return 0;
  10. }
  11. const int M = obstacleGrid.size();
  12. const int N = obstacleGrid[0].size();
  13. vector<vector<int> > ret(M, vector<int>(N, 0));
  14. for (int i = 0; i != M; ++i) {
  15. if (obstacleGrid[i][0]) {
  16. break;
  17. } else {
  18. ret[i][0] = 1;
  19. }
  20. }
  21. for (int i = 0; i != N; ++i) {
  22. if (obstacleGrid[0][i]) {
  23. break;
  24. } else {
  25. ret[0][i] = 1;
  26. }
  27. }
  28. for (int i = 1; i != M; ++i) {
  29. for (int j = 1; j != N; ++j) {
  30. if (obstacleGrid[i][j]) {
  31. ret[i][j] = 0;
  32. } else {
  33. ret[i][j] = ret[i -1][j] + ret[i][j - 1];
  34. }
  35. }
  36. }
  37. return ret[M - 1][N - 1];
  38. }
  39. };

源码分析

  1. 异常处理
  2. 初始化二维矩阵(全0阵),尤其注意遇到障碍物时应break跳出当前循环
  3. 递推路径数
  4. 返回ret[M - 1][N - 1]