码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 63. Unique Paths II

时间:2016-07-07 22:24:51      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:

63. Unique Paths II

  • Total Accepted: 70691
  • Total Submissions:237311
  • Difficulty: Medium

 

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.

 

思路:
关于存储空间的优化,可以看姐妹题:Leetcode 62. Unique Paths

1. 如果地图的左上角定格是障碍,则输出为0;

2. 对于第0行的第j(0<j<n)个,cur[0]=1:

2.1 obstacleGrid[0][j-1]==1(等价于cur[j-1]==0),则cur[j]=0

2.2 obstacleGrid[0][j-1]==0(等价于cur[j-1]==1),则cur[j]=1-obstacleGrid[0][j]

3. 对于第i行(0<i<m):

3.1 对于第0个:

3.1.1 obstacleGrid[i-1][0]==1,cur[0]=0

3.1.2 obstacleGrid[i-1][0]==0,cur[0]=1

3.2 对于第j(0<j<n)个:
3.2.1 obstacleGrid[i][j]==1,cur[j]=0

3.2.2 obstacleGrid[i][j]==0,cur[j]=cur[j-1]+cur[j]

 

代码:

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

 

Leetcode 63. Unique Paths II

标签:

原文地址:http://www.cnblogs.com/Deribs4/p/5651709.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!