[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];
        
    }
};

代码很容易就能看懂。 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值