Skip to content

Instantly share code, notes, and snippets.

@cangoal
Created June 3, 2015 19:04
Show Gist options
  • Save cangoal/c6444642bdf394281580 to your computer and use it in GitHub Desktop.
Save cangoal/c6444642bdf394281580 to your computer and use it in GitHub Desktop.
LeetCode - Unique Paths II
//
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
if(obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0].length == 0)
return 0;
int m = obstacleGrid.length, n = obstacleGrid[0].length;
int[] res = new int[n];
if(obstacleGrid[0][0] == 0) res[0] = 1;
else res[0] = 0;
for(int i=0;i<m;i++)
{
if(obstacleGrid[i][0] == 0) res[0] = res[0];
else res[0] = 0;
for(int j=1;j<n;j++)
{
if(obstacleGrid[i][j] == 1){
res[j] = 0;
}else{
res[j] += res[j-1];
}
}
}
return res[n-1];
}
// better solution
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
int[][] mat = new int[m+1][n+1];
mat[0][1] = 1;
for(int i=1; i<=m; i++){
for(int j=1; j<=n; j++){
if(obstacleGrid[i-1][j-1]!=1)
mat[i][j] = mat[i-1][j]+mat[i][j-1];
}
}
return mat[m][n];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment