leetcode--Unique Paths II

来源:互联网 发布:美化个人自动发卡源码 编辑:程序博客网 时间:2024/06/09 18:16

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.


题意:接着Unique Paths http://blog.csdn.net/crazy__chen/article/details/46408253,如果地图上有障碍物,此障碍物不能通过

在数组中用1表示障碍物,求从起点到终点有多少种走法。


解法1:和Unique Paths一样,使用动态规划。如果当前格子为1,则flag[i][j]设置为0即可。

[java] view plain copy
  1. public class Solution {  
  2.     public int uniquePathsWithObstacles(int[][] obstacleGrid) {  
  3.         int m = obstacleGrid.length;    
  4.         int n = obstacleGrid[0].length;    
  5.         int[][] flag = new int[m][n];    
  6.         if(obstacleGrid[0][0]==1return 0;    
  7.         for(int i=m-1;i>=0;i--){    
  8.             for(int j=n-1;j>=0;j--){         
  9.                 if(obstacleGrid[i][j]==1){//如果是障碍物,不能通过,设为0    
  10.                     flag[i][j] = 0;    
  11.                 }else if(i+1==m&&j+1==n){//如果是终点,初始化为1    
  12.                     flag[i][j] = 1;    
  13.                 }else if(i+1==m){//下边界点    
  14.                     flag[i][j] = flag[i][j+1];    
  15.                 }else if(j+1==n){//右边界点    
  16.                     flag[i][j] = flag[i+1][j];    
  17.                 }else{//其余节点,公式计算    
  18.                     flag[i][j] = flag[i+1][j]+flag[i][j+1];    
  19.                 }    
  20.             }    
  21.         }    
  22.         return flag[0][0];    
  23.     }  
  24. }  

原文链接http://blog.csdn.net/crazy__chen/article/details/46409243

原创粉丝点击