LeetCode---unique-paths-ii(路径个数)

博客围绕矩阵中机器人路径数量问题展开。首先给出无障碍物时,机器人从左上角到右下角的路径数量求解思路,利用dp[i][j]矩阵,满足dp[i][j]=dp[i - 1][j]+dp[i][j - 1]。接着拓展到有障碍物的情况,根据obs[i][j]矩阵判断,若obs[i][j]=0则dp[i][j]=0,否则按上述公式计算。

题目描述

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).

How many possible unique paths are there?

Above is a 3 x 7 grid. How many possible unique paths are there?

Note: m and n will be at most 100.

思路:

111
123
136
1410

                                                    dp[i][j]矩阵

满足   dp[i][j]=dp[i-1][j]+dp[i][j-1];(i>1&&j>1)

class Solution {
public:
    int hash[102][102]={0};
    int uniquePaths(int m, int n) {
        if(m<=0||n<=0) return -1;
        if(m==1||n==1) return 1;
        if(hash[m][n]!=0) return hash[m][n];
        hash[m][n]=uniquePaths(m,n-1)+uniquePaths(m-1,n);
        return hash[m][n];
    }
};

class Solution {
public:
    int uniquePaths(int m, int n) {
        vector<vector<int> >dp(m,vector<int>(n));
        dp[0][0]=1;
        for(int i=0;i<m;++i)
            dp[i][0]=1;
        for(int i=0;i<n;++i)
            dp[0][i]=1;
        for(int i=1;i<m;++i)
            for(int j=1;j<n;++j)
                dp[i][j]=dp[i-1][j]+dp[i][j-1];
        return dp[m-1][n-1];
    }
};

拓展题目 

题目描述

Follow up for "Unique Paths":

Now consider if some obstacles are added to the grids. How many unique paths would there be?

An obstacle and empty space is marked as1and0respectively in the grid.

For example,

There is one obstacle in the middle of a 3x3 grid as illustrated below.

[
  [0,0,0],
  [0,1,0],
  [0,0,0]
]

The total number of unique paths is2.

Note: m and n will be at most 100.

思路:

0000
0101
1000
0000

                                                obs[i][j]矩阵

1111
1012
0013
0014

                                                dp[i][j]矩阵

如果obs[i][j]==0,那么dp[i][j]=0;

如果obs[i][j]!=0,那么dp[i][j]=dp[i-1][j]+dp[i][j-1];(i>1&&j>1)

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int> > &obs) {
        int row=obs.size();
        int col=obs[0].size();
        vector<vector<int> >dp(row,vector<int>(col));
        if(obs[0][0]==1) return 0;
        dp[0][0]=1;
        for(int i=0;i<row;++i)
            if(obs[i][0]!=1) dp[i][0]=1;
            else break;
        for(int i=0;i<col;++i)
            if(obs[0][i]!=1) dp[0][i]=1;
            else break;
        for(int i=1;i<row;++i)
            for(int j=1;j<col;++j)
                if(obs[i][j]!=1) dp[i][j]=dp[i-1][j]+dp[i][j-1];
                else dp[i][j]=0;
        return dp[row-1][col-1];
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值