一、题目
二、代码
class Solution
{
public int uniquePathsWithObstacles(int[][] obstacleGrid)
{
int i,j;
int m,n;
m = obstacleGrid.length;
n = obstacleGrid[0].length;
// System.out.println(" m "+m);
// System.out.println(" n "+n);
int[][] dp = new int[m][n];
for(i=0;i<m;i++)
{
if(obstacleGrid[i][0]==1) break;
dp[i][0] = 1;
}
for(i=0;i<n;i++)
{
if(obstacleGrid[0][i]==1) break;
dp[0][i] = 1;
}
for( i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(i==0||j==0) continue;
else 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];
}
}
三、运行结果
四、附录
二刷
class Solution
{
public int uniquePathsWithObstacles(int[][] obstacleGrid)
{
int i,j;
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
if(obstacleGrid[m-1][n-1]==1) return 0;
int[][] res = new int[m][n];
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(obstacleGrid[i][j] == 1)
{
//System.out.println(" i "+i+" j "+j);
res[i][j] = -1;
}
}
}
for(i=0;i<m;i++)
{
if(res[i][0] != -1) res[i][0] = 1;
else break;
}
for(j=0;j<n;j++)
{
if(res[0][j] !=-1) res[0][j] = 1;
else break;
}
for(i=1;i<m;i++)
{
for(j=1;j<n;j++)
{
if(res[i][j] == -1) continue;
if(res[i-1][j] == -1 &&res[i][j-1] != -1) res[i][j] = res[i][j-1];
else if(res[i-1][j] != -1 &&res[i][j-1] == -1) res[i][j] = res[i-1][j];
else if(res[i-1][j] == -1 &&res[i][j-1] == -1) res[i][j] = 0;
else res[i][j] = res[i][j-1] + res[i-1][j];
}
}
return res[m-1][n-1];
}
}