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

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

題意:

給定一個 M * N 的矩陣,其中1代表障礙物,0代表有路可走,規定每一步只能向右或者向下,求從左上角(0,0)到右下角(M-1,N-1)可走的路的數目。

分析:

用動態規劃解(→_→遞歸應該會超時);

以f【i】【j】代表從(0,0)走到(i,j)時的路徑數;首先判斷(0,0)是不是障礙物,如果是則無路可走直接返回0,否則,f【0】【0】= 1;

由於第一行處於最上面,只能從左邊往右走過來,如果該座標有障礙物,從該座標起到第一行末f【0】【j】都等於0,否則f【0】【j】= 1;由於第一列處於最左,只能從上往下走過來,如果該座標有障礙物,從該座標起到第一列末f【i】【0】都等於0,否則f【i】【0】= 1;對於其它位置,都有f【i】【j】= f【i】【j-1】+f【i-1】【j】;

結果返回f【M-1】【N-1】。

C++代碼:

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        int x = obstacleGrid.size();
        int y = obstacleGrid[0].size();
        if(obstacleGrid[0][0])
            return 0;
         for(int j=0; j<y; j++)
            if(!obstacleGrid[0][j])
                obstacleGrid[0][j]=1;
            else
            {
                for(;j<y;j++)
                    obstacleGrid[0][j]=0;
            }
         for(int i=1; i<x; i++)
                if(!obstacleGrid[i][0])
                    obstacleGrid[i][0]=1;
                else
               {
                   for(;i<x;i++)
                    obstacleGrid[i][0]=0;
               }
        for(int i=1; i<x; i++)
             for(int j=1; j<y; j++)
             {
                 if(!obstacleGrid[i][j])
                    obstacleGrid[i][j]=obstacleGrid[i][j-1]+obstacleGrid[i-1][j];
                 else
                    obstacleGrid[i][j]=0;
             }
        return obstacleGrid[x-1][y-1];
    }
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章