1. 程式人生 > >[LeeCode] Unique Paths II解法

[LeeCode] 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.

分析

又是一道動態規劃的題目。動態規劃的大致意思是利用已知解求新問題的解。在這道題中,建立一個m*n的二維陣列,首先將初始位置初始化為1.其他位置全部初始化為0.因為機器人只能往右走和往下走,我們很清楚的知道,走到0,1位置的走法只有1種,走到1,0位置的走法也只有一種,如果沒有任何阻礙的話,1,1位置只能從0,1位置和1,0位置到達。那麼知道了前兩個位置有幾種走法,新位置的走法數就是前兩個位置之和。如果在原地圖中該位置為1,說明不能到達這個地方,然後在新建的二維數組裡填0.比如在原來的地圖中,(1,1)位置為1,那麼經過一步一步移動,可以得知到達(0,2)的走法數為1.那麼到達(1,2)的走法數為(1,1)+(0,2),但是因為(1,1)是0,所以想到達(1,2)只能從(0,2)那裡走過來。到(0,2)的走法是多少,到(1,2)的走法就是多少。就這樣一步一步遍歷整個地圖,最後終點處的數值即為所求。

程式碼

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        int row = obstacleGrid.size();
        int col = obstacleGrid[0].size();
        if(obstacleGrid[0][0]==1) return 0;
        int num[row][col] = {0};
        for(int i=0;i<row;i++)
            for(int j=0;j<col;j++)
            {
                if(obstacleGrid[i][j]==1) {num[i][j]=0;continue;}
                if(i==0&&j==0) {num[i][j] = 1;continue;}
                if(i==0&&j>0) {num[i][j] = num[i][j-1];continue;}
                if(j==0&&i>0) {num[i][j] = num[i-1][j];continue;}
                num[i][j] = num[i-1][j] + num[i][j-1];
            }
        return num[row-1][col-1];
        
    }
};

程式碼很容易就能看懂。