這道題我是用搜索做的 ,用了32ms ,先找到地圖中最低的點,直接dfs搜一遍,然後遍歷所有沒有搜到的點,再搜一次,不過要注意在搜的過程中更新最長的路程。
Description
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
一個人可以從某個點滑向上下左右相鄰四個點之一,當且僅當高度減小。在上面的例子中,一條可滑行的滑坡爲24-17-16-1。當然25-24-23-...-3-2-1更長。事實上,這是最長的一條。
Input
Output
Sample Input
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
25
具體代碼如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int r,c,answer;
int h[102][102],dp[102][102];
int a[4]= {0,0,1,-1},b[4]= {1,-1,0,0}; //用數組來保存四個方向
void run(int x,int y)
{
int xx,yy;
for(int i=0; i<4; i++)
{
xx=x+a[i];
yy=y+b[i];
if(xx<0||xx>=r||yy<0||yy>=c||h[xx][yy]<=h[x][y]||dp[xx][yy]>dp[x][y]+1) //dp[xx][yy]>dp[x][y]+1時不需要進行更新
continue ;
else
{
dp[xx][yy]=dp[x][y]+1;
run(xx,yy);
}
}
return ;
}
int main()
{
int x,y;
while(~scanf("%d %d",&r,&c))
{
answer=x=y=0;
memset(dp,0,sizeof(dp));
for(int i=0; i<r; i++)
{
for(int j=0; j<c; j++)
{
scanf("%d",&h[i][j]);
if(h[i][j]<h[x][y])
{
x=i;
y=j;
}
}
}
dp[x][y]=1;
run(x,y);
for(int i=0; i<r; i++)
for(int j=0; j<c; j++)
if(!dp[i][j])
{
dp[i][j]=1;
run(i,j);
}
for(int i=0; i<r; i++)
for(int j=0; j<c; j++)
{
answer=max(answer,dp[i][j]);
}
printf("%d\n",answer);
}
return 0;
}