题解 | #矩阵最长递增路径#

矩阵最长递增路径

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

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 递增路径的最大长度
     * @param matrix int整型二维数组 描述矩阵的每个数
     * @return int整型
     */
    int max = 0;

    public int solve(int[][] matrix) {
        // write code here
        int n = matrix.length;
        int m = matrix[0].length;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                dfs(matrix, i, j, 1);
            }
        }
        return max;
    }

    public void dfs(int[][] matrix, int i, int j, int len) {
        int temp = matrix[i][j];
        if (i + 1 < matrix.length && matrix[i + 1][j] > temp) {
            dfs(matrix, i + 1, j, len + 1);
        }
        if (i - 1 >= 0 && matrix[i - 1][j] > temp) {
            dfs(matrix, i - 1, j, len + 1);
        }
        if (j + 1 < matrix[0].length && matrix[i][j + 1] > temp) {
            dfs(matrix, i, j + 1, len + 1);
        }
        if (j - 1 >= 0 && matrix[i][j - 1] > temp) {
            dfs(matrix, i, j - 1, len + 1);
        }
        max = Math.max(max, len);
    }
}

}

全部评论

相关推荐

09-25 00:00
已编辑
电子科技大学 Java
球球与墩墩:这不是前端常考的对象扁平化吗,面试官像是前端出来的 const flattern = (obj) => { const res = {}; const dfs = (curr, path) => { if(typeof curr === 'object' && curr !== null) { const isArray = Array.isArray(curr); for(let key in curr) { const newPath = path ? isArray ? `${path}[${key}]` : `${path}.${key}` : key; dfs(curr[key], newPath); } } else { res[path] = curr } } dfs(obj); return res; }
查看3道真题和解析
点赞 评论 收藏
分享
牛客70961307...:你这项目认真的吗?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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