Unique Paths II - LeetCode

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.

思路:DP。

我们用dp[i][j]表示到达matrix[i][j]的全部可能路线数。则当matrix[i][j] = 0,即当前位置没有障碍时,dp[i][j] = dp[i - 1][j] + dp[i][j - 1];否则dp[i][j] = 0。

因此我们有递推公式:dp[i][j] = (1 - matrix[i][j]) * (dp[i - 1][j] + dp[i][j - 1]);

 1 class Solution {
 2 public:
 3     int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
 4         int m = obstacleGrid.size();
 5         if (m == 0) return 0;
 6         int n = obstacleGrid[0].size();
 7         if (n == 0) return 0;
 8         vector<int> tem(n, 0);
 9         vector<vector<int> > dp(m, tem);
10         dp[0][0] = 1 - obstacleGrid[0][0];
11         for (int i = 1; i < m; i++)
12             dp[i][0] = (1 - obstacleGrid[i][0]) * dp[i - 1][0];
13         for (int i = 1; i < n; i++)
14             dp[0][i] = (1 - obstacleGrid[0][i]) * dp[0][i - 1];
15         for (int i = 1; i < m; i++)
16             for (int j = 1; j < n; j++)
17                 dp[i][j] = (1 - obstacleGrid[i][j]) *
18                     (dp[i - 1][j] + dp[i][j - 1]);
19         return dp[m - 1][n - 1];
20     }
21 };

 

posted @ 2015-11-04 11:15  fenshen371  阅读(169)  评论(0编辑  收藏  举报