算法:动态规划(记忆化搜索)
用dp时,最好先想好递归的解法,再转换成记忆化搜索。
#
include<stdio.h>
# define MAX 101
int height[ MAX ][ MAX ];
int flag[ MAX ][ MAX ];
int LongestLength(int i , int j , int r , int c)
{
int max = 0 , a[ 4 ] , k;
if (flag[i][j] != - 1 )
return flag[i][j];
if (i < 0 || j < 0 || i >= r || j >= c)
return 0 ;
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 ;
return max + 1 ;
}
}
int main()
{
int r , 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 );
return 0 ;
}
# define MAX 101
int height[ MAX ][ MAX ];
int flag[ MAX ][ MAX ];
int LongestLength(int i , int j , int r , int c)
{
int max = 0 , a[ 4 ] , k;
if (flag[i][j] != - 1 )
return flag[i][j];
if (i < 0 || j < 0 || i >= r || j >= c)
return 0 ;
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 ;
return max + 1 ;
}
}
int main()
{
int r , 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 );
return 0 ;
}