跳到主要内容

63. 不同路径 II(Medium)

Go 示例

func uniquePathsWithObstacles(obstacleGrid [][]int) int {
if len(obstacleGrid) == 0 || len(obstacleGrid[0]) == 0 { // 空
return 0
}
n, m := len(obstacleGrid), len(obstacleGrid[0]) // 终点有障碍
if obstacleGrid[n - 1][m - 1] == 1 {
return 0
}
dp := make([][]int, n) // 初始化数组
for i:= 0; i < n; i++ {
dp[i] = make([]int, m)
}
for i:= 0; i < n; i++ {
if obstacleGrid[i][0] == 1 {
break
}
dp[i][0] = 1
}
for i:= 0; i < m; i++ {
if obstacleGrid[0][i] == 1 {
break
}
dp[0][i] = 1
}

for i := 1; i < n; i++ {
for j := 1; j < m; j++ {
if obstacleGrid[i][j] == 0 {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
}
}
}

return dp[n - 1][m - 1]
}