算法:动态规划(记忆化搜索)
用dp时,最好先想好递归的解法,再转换成记忆化搜索。
#include<stdio.h>
#defineMAX101
intheight[MAX][MAX];
intflag[MAX][MAX];
intLongestLength(inti,intj,intr,intc)
{
intmax=0,a[4],k;
if(flag[i][j]!=-1)
returnflag[i][j];
if(i<0||j<0||i>=r||j>=c)
return0;
else
{
if(height[i-1][j]>=height[i][j])
a[0]=0;
else
a[0]=LongestLength(i-1,j,r,c);
if(height[i+1][j]>=height[i][j])
a[1]=0;
else
a[1]=LongestLength(i+1,j,r,c);
if(height[i][j-1]>=height[i][j])
a[2]=0;
else
a[2]=LongestLength(i,j-1,r,c);
if(height[i][j+1]>=height[i][j])
a[3]=0;
else
a[3]=LongestLength(i,j+1,r,c);

for(k=0;k<4;k++)
if(a[k]>max)
max=a[k];
flag[i][j]=max+1;
returnmax+1;
}
}
intmain()
{
intr,c,i,j,max=0;
scanf("%d%d",&r,&c);
for(i=0;i<r;i++)
for(j=0;j<c;j++)
{
scanf("%d",height[i]+j);
flag[i][j]=-1;
}
for(i=0;i<r;i++)
for(j=0;j<c;j++)
if(LongestLength(i,j,r,c)>max)
max=LongestLength(i,j,r,c);
printf("%d/n",max);
return0;
}