zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    解题报告:POJ1852 Ants
    解题报告:POJ2573 Bridge(分析建模)
    POJ 3321 Apple Tree(树状数组模板)
    PAT1139 First Contact
    POJ3259 SPFA判定负环
    HDOJ2586 最近公共祖先模板
    树的直径与最近公共祖先
    字符数组_随机存储
    青鸟资料下载
    软件测试(4)_LoadRunner使用
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4110628.html
Copyright © 2011-2022 走看看