leetcode #63 in cpp

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.


The total number of unique paths is 2.


It is almost the same as #62. In this question we have to check if a position(i,j) has obstacle. If it has one, leave dp[i][j] as 0 as it has no paths to destination. 


class Solution {
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        int m = obstacleGrid.size();
        int n = obstacleGrid[0].size();
        if(obstacleGrid[m-1][n-1] == 1) return 0;//if destination has obstacle, it can never be reached
        vector<vector<int>> dp(m, vector<int>(n,0));
        dp[m-1][n-1] = 1;//set destination be 1
        for(int i = m-2; i >=0 && n-1>=0; i --){//right border
            if(obstacleGrid[i][n-1]!=1) dp[i][n-1] = dp[i+1][n-1];//if a position has obstacle, the cell above it would have path 0 to destination.
        for(int i = n-2; i >=0 && m-1 >= 0; i--){//bottom row
            if(obstacleGrid[m-1][i]!=1) dp[m-1][i] = dp[m-1][i+1];//if a position has obstacle, the cells at its left would have path 0 to destination.
        for(int i = m-2; i >= 0; i --){
            for(int j = n-2; j >= 0; j --){
                //if it is obstacle, skip it and leave it as 0. There are no paths from obstacle to destination
                //if not obstacle, then we could calculate the number of paths. 
                if(obstacleGrid[i][j] != 1) dp[i][j] += dp[i+1][j] + dp[i][j+1];
        return dp[0][0];

文章标签: cpp leetcode
个人分类: interview
想对作者说点什么? 我来说一句

LeetCode cpp最新中文题解.pdf

2018年01月10日 866KB 下载



leetcode #63 in cpp