【LeetCode】329. Longest Increasing Path in a Matrix (Hard)

本文介绍了一种寻找矩阵中最长递增路径的算法。通过构建图并进行拓扑排序,结合动态规划方法来求解最大路径长度。适用于四方向移动且不超出边界的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【题目】

Given an integer matrix, find the length of the longest increasing path.

From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).

Example 1:

nums = [
  [9,9,4],
  [6,6,8],
  [2,1,1]
]

Return 4
The longest increasing path is [1, 2, 6, 9].

【解】

建图,如果a < b,则a到b有一条有向边。然后拓扑排序。

然后从拓扑排序排在后面的节点开始用动态规划算从这个节点开始最大的路径长度。然后再找最大的。。。。。。

class Solution {
public:
    int longestIncreasingPath(vector<vector<int>>& matrix) {
        int r = matrix.size();
        if (r == 0) return 0;
        int c = matrix[0].size();
        this->row = r;
        this->col = c;
        vector<pair<int, int>> top_order(row * col);
        vector<vector<int>> path_len(row, vector<int>(col, 0));
        top_sort(matrix, top_order);
        int result = 0;
        for (int i = row * col - 1; i >= 0; i--) {
            int m = 1;
            for (int j = 0; j < 4; j++) {
                int x = top_order[i].first + dx[j], y = top_order[i].second + dy[j];
                if (x < 0 || x >= row || y < 0 || y >= col) continue;
                if (matrix[x][y] > matrix[top_order[i].first][top_order[i].second]) {
                    if (1 + path_len[x][y] > m) {
                        m = 1 + path_len[x][y];
                    }
                }
            }
            path_len[top_order[i].first][top_order[i].second] = m;
            if (result < m) result = m;
        }
        return result;
    }
    void top_sort(vector<vector<int>>& matrix, vector<pair<int, int>>& top_order) {
        int n = row * col - 1;
        vector<vector<bool>> visited(row, vector<bool>(col, false));
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (!visited[i][j]) {
                    visited[i][j] = true;
                    dfs(matrix, top_order, i, j, n, visited);
                }
            }
        }
    }
    void dfs(vector<vector<int>>& matrix, vector<pair<int, int>>& top_order, int sx, int sy, int& n, vector<vector<bool>>& visited) {
        for (int i = 0; i < 4; i++) {
            int x = sx + dx[i], y = sy + dy[i];
            if (x < 0 || x >= row || y < 0 || y >= col || visited[x][y] || matrix[x][y] <= matrix[sx][sy]) continue;
            visited[x][y] = true;
            dfs(matrix, top_order, x, y, n, visited);
        }
        top_order[n] = make_pair(sx, sy);
        n--;
    }
    int dx[4] = { 0, 1, 0, -1 };
    int dy[4] = { 1, 0, -1, 0 };
    int row;
    int col;
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值