leetcode 329. 矩阵中的最长递增路径

题目:329. 矩阵中的最长递增路径 - 力扣(LeetCode)

数据规模很小,排序就够了

cpp 复制代码
struct Node {
    int x;
    int y;
    int val;
    Node* up = nullptr;
    Node* down = nullptr;
    Node* left = nullptr;
    Node* right = nullptr;
    int length = 0;
    Node(int _x, int _y, int _v) {
        x = _x;
        y = _y;
        val = _v;
    }
};
bool myComp(Node* a, Node* b) {
    return a->val < b->val;
}
class Solution {
public:
    int longestIncreasingPath(vector<vector<int>>& matrix) {
        vector<Node*> arr;
        int upIdx, leftIdx;
        for (int i = 0; i < matrix.size(); i++) {
            vector<int>& t = matrix[i];
            for (int j = 0; j < t.size(); j++) {
                Node* node = new Node(i, j, t[j]);
                arr.push_back(node);
                if (i > 0) {
                    upIdx = (i - 1) * t.size() + j;
                    node->up = arr[upIdx];
                    arr[upIdx]->down = node;
                }
                if (j > 0) {
                    leftIdx = i * t.size() + j - 1;
                    node->left = arr[leftIdx];
                    arr[leftIdx]->right = node;
                }
            }
        }
        sort(arr.begin(), arr.end(), myComp);
        int max;
        int ret = 1;
        for (int i = 0; i < arr.size(); i++) {
            Node* node = arr[i];
            max = 0;
            if (node->left && node->left->val < node->val && node->left->length > max) {
                max = node->left->length;
            }
            if (node->right && node->right->val < node->val && node->right->length > max) {
                max = node->right->length;
            }
            if (node->up && node->up->val < node->val && node->up->length > max) {
                max = node->up->length;
            }
            if (node->down && node->down->val < node->val && node->down->length > max) {
                max = node->down->length;
            }
            node->length = max + 1;
            if (node->length > ret) {
                ret = node->length;
            }
        }
        return ret;
    }
};
相关推荐
এ᭄画画的北北1 小时前
力扣-51.N皇后
算法·leetcode
1白天的黑夜11 小时前
前缀和-974.和可被k整除的子数组-力扣(LeetCode)
c++·leetcode·前缀和
1 小时前
LeetCode Hot 100 搜索二维矩阵
算法·leetcode·矩阵
小新学习屋1 小时前
《剑指offer》-算法篇-位运算
python·算法·leetcode·职场和发展·数据结构与算法
鼠鼠一定要拿到心仪的offer1 小时前
Day23-二叉树的层序遍历(广度优先搜素)
数据结构·算法·leetcode
YuTaoShao1 小时前
【LeetCode 热题 100】34. 在排序数组中查找元素的第一个和最后一个位置——二分查找
java·数据结构·算法·leetcode
Swift社区3 小时前
从字符串中“薅出”最长子串:LeetCode 340 Swift 解法全解析
算法·leetcode·swift
吃着火锅x唱着歌5 小时前
LeetCode 1616.分割两个字符串得到回文串
算法·leetcode·职场和发展
Gerry_Liang7 小时前
LeetCode热题100——155. 最小栈
算法·leetcode·职场和发展
Spider_Man8 小时前
从 "字符拼图" 到 "文字魔术":动态规划玩转字符串变形术
javascript·算法·leetcode