63. Unique Paths II 类别:动态规划 难度:medium

来源:互联网 发布:淘宝商家客服兼职 编辑:程序博客网 时间:2024/06/05 06:01

题目:

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.


思路:

这题的思路与 62 Unique Paths 大致相同。 唯一的不同在于,如果某个方格有障碍,那么记录每个方格路径数的数组 res[] 在该单元内被置为 0 。 
方格左上角和右下角只要有一个为障碍,那么结果都是 0. 


程序:

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


0 0
原创粉丝点击