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

[leetcode]Unique Paths II

时间:2014-08-08 23:55:17      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   for   ar   cti   

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.

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]
]

算法思路:

[leetcode]Unique Paths几乎一样,就加上一个判断好了。

代码如下:

 1 public class Solution {
 2     public int uniquePathsWithObstacles(int[][] obstacleGrid) {
 3         if(obstacleGrid == null || obstacleGrid.length == 0) return 0;
 4         int height = obstacleGrid.length;
 5         int width = obstacleGrid[0].length;
 6         int[][] dp = new int[height][width];
 7         for(int i = 0; i < width;i++){
 8             if(obstacleGrid[0][i] == 0){
 9                 dp[0][i] = 1;
10             }else{
11                 break;
12             }
13         }
14         for(int i = 0; i < height;i++){
15             if(obstacleGrid[i][0] == 0){
16                 dp[i][0] = 1;
17             }else{
18                 break;
19             }
20         }
21         for(int i = 1; i < height; i++){
22             for(int j = 1; j < width;j++){
23                 if(obstacleGrid[i][j] == 0)
24                     dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
25             }
26         }
27         return dp[height - 1][width - 1];    
28     }
29 }

 

[leetcode]Unique Paths II,布布扣,bubuko.com

[leetcode]Unique Paths II

标签:style   blog   http   color   io   for   ar   cti   

原文地址:http://www.cnblogs.com/huntfor/p/3900291.html

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