【LeetCode 329】Longest Increasing Path in a Matrix

本文探讨了在一个整数矩阵中寻找最长递增路径的问题,提供了详细的算法实现,包括使用广度优先搜索策略来遍历矩阵,寻找从每个单元格出发的最长递增路径长度。通过两个实例演示了算法的应用过程。

题目描述

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:

Input: nums = 
[
  [9,9,4],
  [6,6,8],
  [2,1,1]
] 
Output: 4 
Explanation: The longest increasing path is [1, 2, 6, 9].

Example 2:

Input: nums = 
[
  [3,4,5],
  [3,2,6],
  [2,2,1]
] 
Output: 4 
Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.

代码

class Solution {
public:
    int longestIncreasingPath(vector<vector<int>>& matrix) {
        if (matrix.empty() || matrix[0].empty()) return 0;
        int n = matrix.size();
        int m = matrix[0].size();
        vector<vector<int>> res(n, vector<int>(m, 0));
        int ans = 0;
        for (int i=0; i<n; ++i) {
            for (int j=0; j<m; ++j) {
                if (res[i][j] == 0) {
                    ans = max(ans, bfs(i, j, res, matrix));
                } 
            }
        }
        return ans;
    }
    
    vector<int> dirs {1, 0, -1, 0, 1};
    
    int bfs(int x, int y, vector<vector<int>>& res, vector<vector<int>>& matrix) {
        if (res[x][y] != 0) return res[x][y];
        int ans = 0;
        for (int i=0; i<4; ++i) {
            int nx = x + dirs[i];
            int ny = y + dirs[i+1];
            if (nx < 0 || nx >= res.size() || ny < 0 || ny >= res[0].size()) {
                continue;
            }
            if (matrix[nx][ny] >= matrix[x][y]) continue;
            ans = max(ans, bfs(nx, ny, res, matrix));
        }
        res[x][y] = ans+1;
        return res[x][y];
    }
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值