/**
* @param {number[][]} obstacleGrid
* @return {number}
*/
/*
* 边界条件:f[0][i] 和 f[i][0] 且 obstacleGrid为0,只能向右或向下到达,因此f[0][i]/f[i][0] && obstacleGrid[0][i]/obstacleGrid[i][0] !== 1 时为1
* 转移方程:obstacleGrid[i][j]===1 时,f[i][j]= 0, obstacleGrid[i][j] === 0 时,f[i][j] = f[i-1][j] + f[i][j-1]
*/
var uniquePathsWithObstacles = function(obstacleGrid) {
let m = obstacleGrid.length;
let n = obstacleGrid[0].length;
let f = new Array(m).fill(0).map(()=> new Array(n).fill(0));
if(obstacleGrid[0][0] === 1){
return 0;
}
for(let i = 0; i < m; i++){
if(obstacleGrid[i][0] === 1){
f[i][0] = 0;
break;
}else{
f[i][0] = 1;
}
}
for(let i = 0; i < n; i++){
if(obstacleGrid[0][i] === 1){
f[0][i] = 0;
break;
}else{
f[0][i] = 1;
}
}
for(let i = 1; i < m; i++){
for(let j = 1; j < n; j++){
if(obstacleGrid[i][j] === 1){
f[i][j] = 0;
}else{
f[i][j] = f[i-1][j] + f[i][j-1]
}
}
}
return f[m-1][n-1];
};
动态规划 -- 63.不同路径2
最新推荐文章于 2024-08-31 21:50:03 发布