首页 > 其他 > 详细

63.Unique Paths II

时间:2015-12-02 17:42:02      阅读:202      评论:0      收藏:0      [点我收藏+]

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.


思路:整体思路和Unique Paths一致,就是当a[i][j]=1时,b[i][j]=0,而不是b[i-1][j]+b[i][j-1]。注意初始化a[i][0]和a[0][i]时,只要第一行或者第一列中出现了障碍物,那么就不可能再接着向右走与向下走了。所以要这样初始化:首先初始化b[0][0],如果a[0][0]=1,那么b[0][0]=0,否则为1。后面继续设置a[][]
  1. class Solution {
  2. private:
  3. int b[101][101];
  4. public:
  5. int uniquePathsWithObstacles(vector<vector<int>>& a) {
  6. int i,j;
  7. int row=a.size();
  8. int col=a[0].size();
  9. b[0][0]= a[0][0]==1? 0:1;
  10. for(i=1;i<row;i++)
  11. b[i][0]= a[i][0]==1? 0:b[i-1][0];
  12. for(i=1;i<col;i++)
  13. b[0][i]= a[0][i]==1? 0:b[0][i-1];
  14. for(i=1;i<row;i++){
  15. for(j=1;j<col;j++){
  16. b[i][j]= a[i][j]==1? 0:b[i-1][j]+b[i][j-1];
  17. }
  18. }
  19. return b[row-1][col-1];
  20. }
  21. };









63.Unique Paths II

原文:http://www.cnblogs.com/zhoudayang/p/5013398.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!