LEETCODE:Unique Paths II

来源:互联网 发布:淘宝刷单 青青岛 编辑:程序博客网 时间:2024/05/29 03:00

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.

动态规划!!!


class Solution {public:    void getPath(vector<vector<int> > &obstacleGrid, int x, int y, int &count) {        int dx = obstacleGrid[0].size();        int dy = obstacleGrid.size();                if(x == dx - 1 && y == dy - 1) {            count ++;            return;        }                if(x == dx - 1) {            for(int ii = y + 1; ii < dy; ii ++) {                if(obstacleGrid[ii][x] == 1) {                    return;                }            }            count ++;            return;        }                if(y == dy - 1) {            for(int ii = x + 1; ii < dx; ii ++) {                if(obstacleGrid[y][ii] == 1) {                    return;                }            }            count ++;            return;        }                // Can move down        if( x < dx - 1 && obstacleGrid[y][x + 1] == 0) {            getPath(obstacleGrid, x + 1, y, count);        }                // Can move right        if(y < dy - 1 && obstacleGrid[y + 1][x] == 0) {            getPath(obstacleGrid, x, y + 1, count);        }    }    int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {        if(obstacleGrid.size() == 0)    return 0;        int x = 0;        int y = 0;        int count = 0;        getPath(obstacleGrid, x, y, count);        return count;    }};





0 0