最长递增路径(YYOJ)

Description

给定一个整数矩阵,找出最长递增路径的长度。

对于每个单元格,你可以往上,下,左,右四个方向移动。 你不能在对角线方向上移动或移动到边界外。

Input

测试样例由多组测试数据组成。每组测试数据第一行输入两个正整数n,m代表矩形的行数和列数( 1 <= n,m <= 500 )

接下来输入n * m 个数,每个数均在int范围内。

输出矩阵中的最长递增路径长度。

Sample Input

3 3
9 9 4
6 6 8
2 1 1

Sample Output

4

代码

#include<bits/stdc++.h>
#include <iostream>
#include <queue>
#include <cmath>
#include <vector>
#include <cstring>
#include <algorithm>
#include <map>
#include <set>
#include <cstdlib>
using namespace std;
long long n,m;
long long dp[505][505];
long long s[505][505];
int dir[4][2]={-1,0,0,-1,1,0,0,1};
int dfs(int x,int y){
 if(dp[x][y])
  return dp[x][y];
 for(int i = 0 ; i < 4 ; i ++){      
  int tx = x + dir[i][0];      
  int ty = y + dir[i][1];       
  if(tx >= 0 && ty >= 0 && tx < n && ty < m && s[tx][ty] > s[x][y]){            
   if(dp[x][y]<dfs(tx,ty))  
    dp[x][y]=dfs(tx,ty);
   else
    dp[x][y]=dp[x][y];
  }   
 }
 return ++dp[x][y];
}
int main(){
    ios::sync_with_stdio(false);
    while(cin>>n>>m){
     memset(dp,0,sizeof(dp));
     for(int i=0;i<n;i++){
      for(int j=0;j<m;j++){
       cin>>s[i][j];
   }
  }
  int ans=0;
  for(int i=0;i<n;i++){
      for(int j=0;j<m;j++){
       ans=max(ans,dfs(i,j));
   }
  }
  cout << ans << endl;
 }
 return 0 ;
}

思路

  1. 每个位置都是可以向上下左右都可以移动的(但是只能向比自己大的方向移动

  2. 9 8 7|.|1 2 3
    6 5 4|.|2 3 4
    3 2 1|.|3 4 5
    输出 5
  3. 利用dp数组储存数据,再次使用时可以直接调用不需要再重复计算
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值