Unique Paths II

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.

http://www.lintcode.com/en/problem/unique-paths-ii/

Discussion

多了一个条件,一个位置上若是obstacle,path number is 0. 这么简单还是没有bug free。见code comment。

Solution


class Solution {
public:
    /**
     * @param obstacleGrid: A list of lists of integers
     * @return: An integer
     */ 
    int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
        // write your code here
        int m = obstacleGrid.size();
        if(m==0) return 0;
        int n = obstacleGrid[0].size();
        vector<int> f(n, 1);
        if(n ==0) return 0;
        if(obstacleGrid[0][0] == 1) return 0;
        for(int i=1; i<n; i++) {
            f[i] = obstacleGrid[0][i]==1 ? 0: f[i-1];
        }
        for(int i = 1; i<m; i++) {
            for (int j=0; j<n; j++) {
                if(j ==0) {//刚开始没有考虑到第一列有可能有obstacle。
                    f[j] = obstacleGrid[i][j]==1 ? 0: f[j];//not f[j-1]
                } else
                    f[j] = obstacleGrid[i][j]==1 ? 0: f[j-1]+f[j];
            }
        }
        return f[n-1];
    }
};

recursion

class Solution {
public:
    /**
     * @param obstacleGrid: A list of lists of integers
     * @return: An integer
     */ 
    int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
        // write your code here
        int m = obstacleGrid.size();
        if(m == 0) return 0;
        int n = obstacleGrid[0].size();
        if(n == 0) return 0;
        if(obstacleGrid[0][0]==1) return 0;
        return helper(obstacleGrid, m-1, n-1);
    }
    int helper(vector<vector<int> > &A, int i, int j) {
        if(i==0 && j==0) {
            return A[i][j]==1 ? 0 : 1;
        }
        if(j==0) {
            return A[i][j]==1 ? 0: helper(A, i-1, j);
        }
        if(i==0) {
            return A[i][j]==1 ? 0 : helper(A, i, j-1);
        }
        if(A[i][j]==1) return 0;
        return helper(A, i-1, j) + helper(A, i, j-1);
    }
};

results matching ""

    No results matching ""