其他分享
首页 > 其他分享> > leetcode 地图分析[动态规划]

leetcode 地图分析[动态规划]

作者:互联网

var arr = [[1,0,1],[0,0,0],[1,0,1]]
function name(arr) {

    let dp = new Array(arr.length).fill(0).map(v => new Array(arr[0].length).fill(0))
    let l = dp.length
    let w = dp[0].length
    let max = 0
    for (let i = 0; i < l; i++) {

        for (let j = 0; j < w; j++) {

            if (arr[i][j] === 1) {
                continue
            }
            if (i > 0 && j > 0) {
                dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1)

            } else if (i > 0 && j == 0) {
                dp[i][j] = dp[i - 1][j] + 1

            } else {
                dp[i][j] = dp[i][j - 1] + 1

            }
            max = Math.max(dp[i][j], max)

        }
    }
    let tl = l - 1
    let tw = w - 1
    for (let i = tl; i >= 0; i--) {

        for (let j = tw; j >= 0; j--) {

            if (arr[i][j] === 1) {
                continue
            }
            if (i < tl && j < tw) {
                dp[i][j] = Math.min(dp[i + 1][j] + 1, dp[i][j + 1] + 1, dp[i][j])

            } else if (i < tl && j == tw) {
                dp[i][j] = Math.min(dp[i + 1][j] + 1, dp[i][j])

            } else if (i == tl && j < tw) {
                dp[i][j] = Math.min(dp[i][j + 1] + 1, dp[i][j])

            }
            max = Math.max(dp[i][j], max)


        }


    }
    console.log(dp);

}
name(arr)
	
	```

标签:arr,max,地图分析,let,Math,tw,动态,leetcode,dp
来源: https://blog.csdn.net/qq_42653212/article/details/121714246