leetcode------Unique Paths II
标题: | Unique Paths II |
通过率: | 28% |
难度: | 中等 |
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.
与第一个版本一样,但是原始数组中会出现1的情况那么针对1来处理,如果遇到1则将其置-1,然后在路径相加中如果是-1则不进行相加
代码如下:
1 public class Solution { 2 public int uniquePathsWithObstacles(int[][] obstacleGrid) { 3 int m=obstacleGrid.length; 4 int n=obstacleGrid[0].length; 5 boolean flag=true; 6 if(obstacleGrid[0][0]==1)return 0; 7 for(int i=0;i<m;i++){ 8 if(obstacleGrid[i][0]!=1&&flag) 9 obstacleGrid[i][0]=1; 10 else { 11 obstacleGrid[i][0]=-1; 12 flag=false; 13 } 14 } 15 flag=true; 16 for(int i=1;i<n;i++){ 17 if(obstacleGrid[0][i]!=1&&flag) 18 obstacleGrid[0][i]=1; 19 else { 20 obstacleGrid[0][i]=-1; 21 flag=false; 22 } 23 } 24 for(int i=1;i<m;i++){ 25 for(int j=1;j<n;j++){ 26 if(obstacleGrid[i][j]!=1){ 27 if(obstacleGrid[i-1][j]==-1&&obstacleGrid[i][j-1]==-1) 28 obstacleGrid[i][j]=0; 29 if(obstacleGrid[i-1][j]==-1) 30 obstacleGrid[i][j]+=obstacleGrid[i][j-1]; 31 else if(obstacleGrid[i][j-1]==-1) 32 obstacleGrid[i][j]+=obstacleGrid[i-1][j]; 33 else obstacleGrid[i][j]=obstacleGrid[i-1][j]+obstacleGrid[i][j-1]; 34 } 35 else{ 36 obstacleGrid[i][j]=-1; 37 } 38 } 39 } 40 if(obstacleGrid[m-1][n-1]==-1)return 0; 41 else 42 return obstacleGrid[m-1][n-1]; 43 44 } 45 }