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

矩阵最长递增路径

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

using System;
using System.Collections.Generic;


class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 递增路径的最大长度
     * @param matrix int整型二维数组 描述矩阵的每个数
     * @return int整型
     */
    int[,] memory;
    List<List<int>> matrix;
    int m,n;
    public int solve (List<List<int>> matrix) {
        this.matrix = matrix;
        m = matrix.Count;
        n = matrix[0].Count;
        memory = new int[m,n];
        int res = 0;
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n;j++){
                res = Math.Max(res, Search(i,j));
                //Console.WriteLine(memory[i,j]);
            }
        }
        return res;
    }
    public int Search(int x, int y){
        if(memory[x,y] != 0) return memory[x,y];
        memory[x,y] = 1;
        if(x > 0 && matrix[x][y] < matrix[x - 1][y]) memory[x,y] = Math.Max(memory[x,y],Search(x - 1, y)+1);
        if(y > 0 && matrix[x][y] < matrix[x][y - 1]) memory[x,y] = Math.Max(memory[x,y],Search(x, y - 1)+1);
        if(x < m-1 && matrix[x][y] < matrix[x + 1][y]) memory[x,y] = Math.Max(memory[x,y],Search(x + 1, y)+1);
        if(y < n-1 && matrix[x][y] < matrix[x][y + 1]) memory[x,y] = Math.Max(memory[x,y],Search(x, y + 1)+1);

        return memory[x,y];
    }
}

全部评论

相关推荐

码农索隆:单休一个月少休息4天,一年就是48天,平时节假日,别人3天假期,单休的两天
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-07 11:30
仁者伍敌:kpi都懒得刷了属于是
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-07 13:35
虽然不怎么光彩,经过这件事,可能我真的要去认同“面试八股文早该淘汰!不会用AI作弊的程序员=新时代文盲!”这句话了
HellowordX:Ai的出现是解放劳动力的,不是用来破坏公平竞争环境的,这样下去,轻则取消所有线上面试,严重了会影响整个行业对所有人产生影响,企业会拉高入职考核各种离谱考核会层出不穷
你找工作的时候用AI吗?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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