Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/kingslave1/article/details/78160535
description:
" Different paths " follow-up question now consider the grid there is an obstacle, so there will be a different path how many?
Grid barriers and empty positions 1 and 0 respectively represented.
Precautions
m and n are not more than 100
Example:
There follows a 3x3 grid of obstacles:
[
[0,0,0],
[0,1,0],
[0,0,0]
]
There are two different paths from top left to bottom right.
answer:
public class Solution {
/*
* @param obstacleGrid: A list of lists of integers
* @return: An integer
*/
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
if(obstacleGrid==null) {
return 0;
}
int m=obstacleGrid.length;
int n=obstacleGrid[0].length;
if(obstacleGrid[0][0]==1) {
return 0;
}
int [][]dp=new int[m][n];
dp[0][0]=1;
int i=1;
for(;i<m;i++) {
dp[i][0]=1;
if(obstacleGrid[i][0]==1||dp[i-1][0]==0) {
dp[i][0]=0;
}
}
int j=1;
for(;j<n;j++) {
dp[0][j]=1;
if(obstacleGrid[0][j]==1||dp[0][j-1]==0) {
dp[0][j]=0;
}
}
for(i=1;i<m;i++) {
for(j=1;j<n;j++) {
if(obstacleGrid[i][j]==1) {
dp[i][j]=0;
}else {
dp[i][j]=dp[i-1][j]+dp[i][j-1];
}
}
}
return dp[m-1][n-1];
}
};