[Leetcode] 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.

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.

 

将obstacle标记为-1,其余基本跟上一题一样。

 

 1 class Solution {

 2 public:

 3     int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {

 4         int m = obstacleGrid.size();

 5         int n = obstacleGrid[0].size();

 6         int i, j;

 7         for (i = 0; i < m; ++i) {

 8             for (j = 0; j < n; ++j) {

 9                 obstacleGrid[i][j] = -obstacleGrid[i][j];

10             }

11         }

12         for (i = 0; i < m; ++i) {

13             if (obstacleGrid[i][0] == -1) break;

14             obstacleGrid[i][0] = 1;

15         }

16         for (j = 0; j < n; ++j) {

17             if (obstacleGrid[0][j] == -1) break;

18             obstacleGrid[0][j] = 1;

19         }

20         for (i = 1; i < m; ++i) {

21             for (j = 1; j < n; ++j) {

22                 if (obstacleGrid[i][j] == -1) continue;

23                 obstacleGrid[i][j] += (obstacleGrid[i-1][j] == -1) ? 0 : obstacleGrid[i-1][j];

24                 obstacleGrid[i][j] += (obstacleGrid[i][j-1] == -1) ? 0 : obstacleGrid[i][j-1];

25             }

26         }

27         return (obstacleGrid[m-1][n-1] == -1) ? 0 : obstacleGrid[m-1][n-1];

28     }

29 };

 

你可能感兴趣的:(LeetCode)