Description
在一个R*C(R,C<=100)的整形矩阵上找一条高度严格递减的最长路。起点任意,但是每次只能沿着上下左右四个方向之一走一格,并且不能走出矩阵外。如图所示,最长高度按照25,24,23,…,1走,长度为25
01 02 03 04 05
16 17 18 19 06
15 24 25 20 07
14 23 22 21 08
13 12 11 10 09
Input
第一行输入多少组数据T
一个字符串代表name,接着输入R,C
接下来输入矩阵
Output
共T组数据
每行输出name+":"+" "+最大长度
Sample Input
2
Feldberg 10 5
56 14 51 58 88
26 94 24 39 41
24 16 8 51 51
76 72 77 43 10
38 50 59 84 81
5 23 37 71 77
96 10 93 53 82
94 15 96 69 9
74 0 62 38 96
37 54 55 82 38
Spiral 5 5
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
Sample Output
Feldberg: 7
Spiral: 25
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cstring>
using namespace std;
int map[105][105];
int d[105][105];
int movey[4]={0,0,1,-1};
int movex[4]={-1,1,0,0};
int r,c;
int dfs(int i,int j)
{
if(d[i][j]!=-1) //说明此时状态已经是最大了
return d[i][j];
d[i][j]=1;
for(int k=0;k<4;k++)
{
int tempx=i+movex[k];
int tempy=j+movey[k];
if((tempx>=1)&&(tempy>=1)&&(tempx<=r)&&(tempy<=c))
{
if(map[i][j]>map[tempx][tempy])
{
d[i][j]=max(d[i][j],dfs(tempx,tempy)+1);
}
}
}
return d[i][j];
}
int main()
{
string name;
int n=0;
cin>>n;
for(int z=1;z<=n;z++)
{
cin>>name;
memset(map,0,sizeof(map));
memset(d,-1,sizeof(d));
scanf("%d%d",&r,&c);
for(int i=1;i<=r;i++)
for(int j=1;j<=c;j++)
scanf("%d",&map[i][j]);
int maxx=0;
for(int i=1;i<=r;i++)
for(int j=1;j<=c;j++)
{
maxx=max(maxx,dfs(i,j));
}
cout<<name<<": "<<maxx<<endl;
}
return 0;
}
本文探讨在限定条件下的矩阵中寻找最长严格递减路径的问题。通过深度优先搜索算法,实现对不同起点路径的最大长度求解,适用于算法竞赛及图论研究。

5178

被折叠的 条评论
为什么被折叠?



