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

The total number of unique paths is 2.

在一个m*n的点阵中,从左上角到右下角,每次只能向下或者向右,并且有障碍物。求最多有几种走法?


思路


1 承接上一题 http://blog.csdn.net/xift810/article/details/22218893,这道题目用dp来做,并且需要数组记录。

2 可以想到到每个点的走法总数,是它上面一个点和它左面一个点总数的和。

3 用一个相同的二维数组记录到相应的点的总数。其中当对应障碍的时候,为0。


代码


public int uniquePathsWithObstacles(int[][] obstacleGrid) {
	        int row = obstacleGrid.length;
	        if(row==0){
	            return 0;
	        }
	        int col = obstacleGrid[0].length;
	        if(col==0){
	            return 0;
	        }
	        int[][] ways = new int[row][col];
	        boolean fuckingblock = false;
	        for(int i=0;i<row;i++){
	            if(fuckingblock||obstacleGrid[i][0]==1){
	                ways[i][0]=0;
	                fuckingblock=true;
	                continue;
	            }
	            ways[i][0]=1;
	        }
	      
	        fuckingblock = false;
	        for(int j=0;j<col;j++){
	            if(fuckingblock||obstacleGrid[0][j]==1){
	                ways[0][j]=0;
	                fuckingblock=true;
	                continue;
	            }
	            ways[0][j]=1;
	        }
	     
	        for(int i=1;i<row;i++){
	            for(int j=1;j<col;j++){
	                if(obstacleGrid[i][j]==1){
	                    ways[i][j]=0;
	                        continue;
	                }
	                
	                ways[i][j]=ways[i][j-1]+ways[i-1][j];
	            }
	        }
	      
	        return ways[row-1][col-1];
	    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值