[leedcode 63] 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
.
public class Solution { public int uniquePathsWithObstacles(int[][] obstacleGrid) { //本题和上一题的不同是增加了障碍,如何结合动态规划考虑障碍是关键 //通过分析本题,如果该位置有障碍,那么到达该位置的路径就是0; //通过这个思路,只需要在计算a[i][j]时,考虑obstacleGrid[i][j]是否为1即可 //需要注意求第一行和第一列,因为前面的障碍会使得后面的所有路径都堵塞,因此最好的办法是设置两个标记 //flag代表列标记,flag1代表行标记 int m=obstacleGrid.length; int n=obstacleGrid[0].length; int a[][]=new int[m][n]; int flag=0; int flag1=0; for(int i=0;i<m;i++){ if(flag==0&&obstacleGrid[i][0]==0){ a[i][0]=1; }else{ a[i][0]=0; flag=1; } for(int j=0;j<n;j++){ if(i==0){ if(flag1==0&&obstacleGrid[i][j]==0) a[i][j]=1; else { a[i][j]=0; flag1=1; } } if(i>0&&j>0){ if(obstacleGrid[i][j]==1){ a[i][j]=0; }else{ a[i][j]=a[i-1][j]+a[i][j-1]; } } } } return a[m-1][n-1]; } }