Unique Paths II

Dynamic Programming

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 as 1 and 0 respectively 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 is 2.

Note: m and n will be at most 100.

在上一题的基础上,加入了障碍,只要将有障碍的地方的路径设置为0,就可以了。

C++实现代码:

#include<iostream>
#include<vector>
using namespace std;

class Solution
{
public:
    int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid)
    {
        if(obstacleGrid.empty()||obstacleGrid[0].empty())
            return 0;
        int m=obstacleGrid.size();
        int n=obstacleGrid[0].size();
        int path[m][n];
        int i,j;
        if(obstacleGrid[0][0]==1)
            return 0;
        path[0][0]=1;
        for(i=1; i<m; i++)
        {
            if(obstacleGrid[i][0]==1)
                path[i][0]=0;
            else
                path[i][0]=path[i-1][0];
        }
        for(j=1; j<n; j++)
        {
            if(obstacleGrid[0][j]==1)
                path[0][j]=0;
            else
                path[0][j]=path[0][j-1];
        }
        for(i=1; i<m; i++)
        {
            for(j=1; j<n; j++)
            {
                if(obstacleGrid[i][j]==1)
                    path[i][j]=0;
                else
                    path[i][j]=path[i-1][j]+path[i][j-1];
            }
        }
        return path[m-1][n-1];
    }
};

int main()
{
    Solution s;
    vector<vector<int> > vec= {{0,0,0},{0,1,0},{0,0,0}};
    cout<<s.uniquePathsWithObstacles(vec)<<endl;
}
原文地址:https://www.cnblogs.com/wuchanming/p/4110628.html