zoukankan      html  css  js  c++  java
  • LeetCode 63. Unique Paths II

    A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

    The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

    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.

    Note: m and n will be at most 100.

    Example 1:

    Input:
    [
      [0,0,0],
      [0,1,0],
      [0,0,0]
    ]
    Output: 2
    Explanation:
    There is one obstacle in the middle of the 3x3 grid above.
    There are two ways to reach the bottom-right corner:
    1. Right -> Right -> Down -> Down
    2. Down -> Down -> Right -> Right

    解答:

    这道题和62很相似,区别在于多了障碍物,不过仍然是用动态对规划的方式,有障碍物的位置对路线数量的贡献为0,更新方法仍然类似,不过可以直接在原来数组上进行更新,不需要新开辟空间

    代码如下:

     1 class Solution {
     2 public:
     3     int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
     4         if (obstacleGrid[0][0] == 1)
     5             return 0;
     6         int row = obstacleGrid.size();
     7         int col = obstacleGrid[0].size();
     8         obstacleGrid[0][0] = 1;
     9         for (int i = 1; i < row; i++)
    10         {
    11             if (obstacleGrid[i][0] == 0)
    12                 obstacleGrid[i][0] = obstacleGrid[i - 1][0];
    13             else 
    14                 obstacleGrid[i][0] = 0;
    15         }
    16         for (int i = 1; i < col; i++)
    17         {
    18             if (obstacleGrid[0][i] == 0)
    19                 obstacleGrid[0][i] = obstacleGrid[0][i - 1];
    20             else 
    21                 obstacleGrid[0][i] = 0;
    22         }
    23         for (int i = 1; i < row; i++)
    24             for (int j = 1; j < col; j++)
    25             {
    26                 if (obstacleGrid[i][j] == 0)
    27                     obstacleGrid[i][j] = obstacleGrid[i - 1][j] + obstacleGrid[i][j - 1];
    28                 else
    29                     obstacleGrid[i][j] = 0;
    30             }
    31         return obstacleGrid[row - 1][col - 1];
    32                 
    33     }
    34 };

    时间复杂度:O(m*n)

    空间复杂度:O(1)

  • 相关阅读:
    【Hadoop】HDFS的运行原理
    ZOOKEEPER3.3.3源码分析(四)对LEADER选举过程分析的纠正
    zookeeper源码分析二FASTLEADER选举算法
    面试题9:用两个栈实现队列
    面试题7:重建二叉树
    C/C++实现链表的常用操作
    扩展卡尔曼滤波(EKF)实现三维位置估计
    毕业论文思路
    链表常用操作
    关于指针
  • 原文地址:https://www.cnblogs.com/dapeng-bupt/p/10350779.html
Copyright © 2011-2022 走看看