题解 | 矩阵最长递增路径

矩阵最长递增路径

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

#include<vector>
using namespace std;
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 递增路径的最大长度
     * @param matrix int整型vector<vector<>> 描述矩阵的每个数
     * @return int整型
     */
    int solve(vector<vector<int> >& matrix) {
        if (matrix.empty() || matrix[0].empty()) return 0;
        int row = matrix.size();
        int col = matrix[0].size();
        int* path = new int[row * col];

        for (int i = 0; i < row; ++i) {
            for (int j = 0; j < col; ++j) {
                path[i * col + j] = matrix[i][j];
            }
        }
        int* rec = new int[row * col]();
        int a=0;
        bool is = false;
        int max=0;
    int total=0;
    for(int i=0;i<row;i++){
        for(int j=0;j<col;j++){
            rec[i*col+j]=1;
            s(i,j,path,rec,&total,col,row,&max);
            rec[i*col+j]=0;
        }
    }return max+1;
    }void s(int x,int y,int* path,int* rec,int* total,int col,int row,int* max){
    //rec[x*col+y]=1;
    if(x>=1){
        if(path[(x-1)*col+y]>path[x*col+y]&&rec[(x-1)*col+y]==0){
            rec[(x-1)*col+y]=1;
            (*total)++;
            s(x-1,y,path,rec,total,col,row,max);
            (*total)--;
            rec[(x-1)*col+y]=0;
        }
    }if(x+1<row){
        if(path[(x+1)*col+y]>path[x*col+y]&&rec[(x+1)*col+y]==0){
            rec[(x+1)*col+y]=1;
            (*total)++;
            s(x+1,y,path,rec,total,col,row,max);
            (*total)--;
            rec[(x+1)*col+y]=0;
        }
    }if(y>=1){
        if(path[x*col+y-1]>path[x*col+y]&&rec[x*col+y-1]==0){
            rec[x*col+y-1]=1;
            (*total)++;
            s(x,y-1,path,rec,total,col,row,max);
            (*total)--;
            rec[x*col+y-1]=0;
        }
    }if(y+1<col){
        if(path[x*col+y+1]>path[x*col+y]&&rec[x*col+y+1]==0){
            rec[x*col+y+1]=1;
            (*total)++;
            s(x,y+1,path,rec,total,col,row,max);
            (*total)--;
            rec[x*col+y+1]=0;
        }
    }if(*total>*max){
        (*max)=(*total);
    }
}
};

全部评论
content://com.baidu.input_huawei/external_cache/image_cache/923de6eed095d949be167b49a332547f9ea0fe273f1237d904375c405cb6715e_wbg.png
1 回复 分享
发布于 04-09 21:46 陕西
点赞 回复 分享
发布于 04-09 21:39 北京

相关推荐

caicaidog:现实里没实习的还是占多数的
点赞 评论 收藏
分享
03-23 23:00
黄淮学院 Java
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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