Longest Increasing Path in a Matrix

本文介绍了一种算法,用于寻找给定整数矩阵中最长的递增路径。该算法通过对每个单元格进行深度优先搜索,并利用记忆化来避免重复计算,从而高效地找到从任意起点开始的最长递增路径。

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

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:

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

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

Example 2:

nums = [
  [3,4,5],
  [3,2,6],
  [2,2,1]
]

Return 4
The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.

解析:

求以每个点为起点求满足条件的最长递增路径,对每个点的求法是求大于当前点的周围四个点中为起点的最大值+1为当前点的最长路径。


代码:

class Solution {
public:
    int longestIncreasingPath(vector<vector<int>>& matrix) {
        if (matrix.empty())
        return 0;
        
        int row=matrix.size();
        int col=matrix[0].size();
        int ans=0;
        vector<vector<int>>vis(row,vector<int>(col,0));
        for (int i=0; i<row; i++)
        {
            for (int j=0; j<col; j++)
            {
                int res=0;
                
               
                dfs(matrix,i,j,res,vis);
                ans=max(ans,res);
            }
        }
        return ans;
        
    }
    
    void dfs(vector<vector<int>>&matrix,int row,int col,int &res,vector<vector<int>>&vis)
    {
        if (vis[row][col])
        {
            res=vis[row][col];
            return ;
        }
        int dx[4]={0,1,0,-1};
        int dy[4]={-1,0,1,0};
        int height=matrix.size();
        int width=matrix[0].size();
        int sum=0;
        int maxsizhou=0;
        for (int i=0; i<4; i++)
        {
            int posy=row+dy[i];
            int posx=col+dx[i];
            if (posy<0||posy>=height||posx<0||posx>=width)
            continue;
            if (matrix[posy][posx]<=matrix[row][col])
            {
                continue;
            }
            sum++;
            if (vis[posy][posx])
            {
                maxsizhou=max(maxsizhou,vis[posy][posx]);
               // res=max(res,vis[posy][posx]+1);
            }
            else
            {
                int tempres=0;
                dfs(matrix,posy,posx,tempres,vis);
                maxsizhou=max(maxsizhou,tempres);
            }
        }
        
        
        if (sum==0)
        {
            res=1;
            vis[row][col]=1;
        }
        else
        {
            res=maxsizhou+1;
            vis[row][col]=res;
        }
       return ;
    
    }
    
    
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值