63. Unique Paths II

来源:互联网 发布:linux教程pdf 编辑:程序博客网 时间:2024/05/17 07:43

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.

这道题可以借鉴Unique Path的动态规划思路,但是还要考虑左边界和上边界的特殊情况。为了解决边界的问题,我们可以在方格的左边和上边各加一个“边框”,即声明整数数组paths[m+1][n+1]而不是paths[m][n]。其中paths[0][1]初始化为1,其余格子初始化为0。这样从左到右,从上到下计算,可以巧妙地解决边界的特殊情况。

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