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 ;
}
思路
- 每个位置都是可以向上下左右都可以移动的(但是只能向比自己大的方向移动
- 例
9 8 7|.|1 2 3
6 5 4|.|2 3 4
3 2 1|.|3 4 5
输出 5 - 利用dp数组储存数据,再次使用时可以直接调用不需要再重复计算