63. Unique Paths II (Array, DP)

##### 题目描述:

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?

##### 分析:

典型的动态规划题目。

不考虑障碍的话,节点可以分为两种:除了第一行和第一列的节点之外的节点和首行首列的节点。

首航首列的节点只能从其上方或者左边的节点到达,一旦其中出现一个障碍,那么其下方的/右方的元素可抵达的路径为0条。

其他节点可以从其上方或者左方的元素抵达。路径数就是两种之和。我们直接在本地依次更新路径数,不需要额外的空间。

先从第一行和第一列分析:

  1. 首先看(0,0)元素,如果是障碍那么直接返回0.
  2. 从首行看,如果该位置为0(不是障碍),且左边为1(路径数)。那么设为1.
  3. 从首列看,如果该位置为0且上方为1 ,那么设为1.
  4. 然后从非首行首列元素依次迭代下去直到最后的目的地
  5. Time Complexity: O(M×N). The rectangular grid given to us is of size M \times NM×N and we process each cell just once.
  6. Space Complexity: O(1) We are utilizing the obstacleGrid as the DP array. Hence, no extra space.
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
            if(obstacleGrid == null || obstacleGrid[0][0]==1)
                return 0;
            int row = obstacleGrid.length;
            int col = obstacleGrid[0].length;
            obstacleGrid[0][0]=1;
            for(int i=1;i<row;i++){
                //set the first column
                if(obstacleGrid[i][0]==0 && obstacleGrid[i-1][0]==1)
                    obstacleGrid[i][0] = 1;
                else
                    obstacleGrid[i][0] = 0;
            }
            for(int i=1;i<col;i++){
                //set the first row
                if(obstacleGrid[0][i]==0 && obstacleGrid[0][i-1]==1)
                    obstacleGrid[0][i] = 1;
                else
                    obstacleGrid[0][i] = 0;
            }
            
            for(int i=1;i<row;i++){
                for(int j=1;j<col;j++){
                    if(obstacleGrid[i][j]!=1)
                        obstacleGrid[i][j] = obstacleGrid[i][j-1] + obstacleGrid[i-1][j];
                    else
                        obstacleGrid[i][j]=0;
                }        
            }
            return obstacleGrid[row-1][col-1];
        }

猜你喜欢

转载自blog.csdn.net/shulixu/article/details/85722951