题解 | 矩阵最长递增路径

矩阵最长递增路径

https://www.nowcoder.com/practice/7a71a88cdf294ce6bdf54c899be967a2

没看到有JavaScript的代码,贴一个在这里

思路:

  • 用深度优先查找dfs
  • dp是动态规划数组,便于在for循环中减少dfs次数
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 递增路径的最大长度
 * @param matrix int整型二维数组 描述矩阵的每个数
 * @return int整型
 */
function solve(matrix) {
    // write code here
    const mR = matrix.length;
    const mC = matrix[0].length;
    const steps = [
        [1, 0],
        [0, 1],
        [-1, 0],
        [0, -1],
    ];
    const dp=new Array(mR).fill(0).map((_)=>new Array(mC).fill(0))
    let maxLen = 0;
    const dfs = (i, j) => {
        if(dp[i][j]>0) {
            return dp[i][j]
        }
        let maxPath=1
        for (let [r, c] of steps) {
            let curI = i + r;
            let curJ = j + c;
            if (
                curI >= 0 &&
                curI < mR &&
                curJ >= 0 &&
                curJ < mC &&
                matrix[curI][curJ] > matrix[i][j]
            ) {
                maxPath=Math.max(maxPath,1+dfs(curI,curJ))
            }
        }
        dp[i][j]=maxPath
        return dp[i][j]
    };
    for(let i=0;i<mR;i++){
        for(let j=0;j<mC;j++){
            maxLen=Math.max(maxLen,dfs(i,j))
        }
    }
    return maxLen
}
module.exports = {
    solve: solve,
};

全部评论

相关推荐

12-11 14:24
门头沟学院 Java
牛客35720396...:不要用boss,全是骗
点赞 评论 收藏
分享
10-28 17:30
已编辑
华东交通大学 Java
想进开水团喝开水:字节的hr的本职工作就是黄金矿工
秋招笔试记录
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务