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

<LeetCode OJ> 63. Unique Paths II

时间:2016-01-08 22:15:33      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

63. Unique Paths II

My Submissions
Total Accepted: 55136 Total Submissions: 191949 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.

Subscribe to see which companies asked this question

Hide Similar Problems
 (M) Unique Paths





























//思路首先:
//此题与原问题相较,变得是什么?
//1,此障碍物下面和右边将不在获得来自于此的数量,也可以理解为贡献为0
//2,有障碍的地方也将无法到达(这一条开始时没想到,总感觉leetcode题目意思不愿意说得明了),可能输数直接为0
class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        int m=obstacleGrid.size();
        int n=obstacleGrid[0].size();
        vector< vector<int> >  result(m+1);   
        for(int i=0;i <=m ;i++)   
            result[i].resize(n+1);//设置数组的大小m+1行,n+1列   
        //初始化一定要正确,否则错无赦    
        result[1][1]= obstacleGrid[0][0]==1? 0:1;    
        for(int i=2;i<=n;i++)  
            result[1][i]=obstacleGrid[0][i-1]==1?0:result[1][i-1];//由上一次来推到  
        for(int i=2;i<=m;i++)  
            result[i][1]=obstacleGrid[i-1][0]==1?0:result[i-1][1];  
            
        for(int i=2;i<=m;i++)  
            for(int j=2;j<=n;j++)  
                result[i][j]=obstacleGrid[i-1][j-1]==1?0:result[i-1][j]+result[i][j-1];  //一旦当前有石头就无法到达,直接置零
            
        return result[m][n];
    }
};





<LeetCode OJ> 63. Unique Paths II

标签:

原文地址:http://blog.csdn.net/ebowtang/article/details/50485468

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