LeetCode63 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. (Medium)
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.
分析:
上一题的follow-up,加上了障碍物,思路一样,只是障碍物处dp[i][j] = 0;
代码:
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 dp[m][n]; 7 memset(dp,0,sizeof(dp)); 8 for (int i = 0; i < n; ++i) { 9 if (obstacleGrid[0][i] == 1) { 10 break; 11 } 12 dp[0][i] = 1; 13 } 14 for (int i = 0; i < m; ++i) { 15 if (obstacleGrid[i][0] == 1) { 16 break; 17 } 18 dp[i][0] = 1; 19 } 20 for (int i = 1; i < m; ++i) { 21 for (int j = 1; j < n; ++j) { 22 if (obstacleGrid[i][j] == 1) { 23 dp[i][j] = 0; 24 } 25 else { 26 dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; 27 } 28 } 29 } 30 return dp[m - 1][n - 1]; 31 } 32 };
注:为什么这道题里dp[m][n] = {0}不能把二维数组初始化为0了......