hoj1078

记忆化搜索,使用dfs,从0,0点开始,把每个点对应的剩下路程所能得到的最大值存入f数组。

View Code
   
     
#include < iostream >
#include
< cstdio >
#include
< cstdlib >
#include
< cstring >
#include
< vector >
#include
< cmath >
#include
< queue >
using namespace std;

#define maxn 105

int map[maxn][maxn];
int f[maxn][maxn];
int ans, fans, n, m;
int dir[ 4 ][ 2 ] =
{
{
1 , 0 },
{
0 , 1 },
{
- 1 , 0 },
{
0 , - 1 } };

void input()
{
for ( int i = 0 ; i < n; i ++ )
for ( int j = 0 ; j < n; j ++ )
scanf(
" %d " , & map[i][j]);
}

bool ok( int x, int y)
{
if (x < 0 || y < 0 || x >= n || y >= n)
return false ;
return true ;
}

int dfs( int x, int y)
{
if (f[x][y] != - 1 )
return f[x][y];
int ans = 0 ;
for ( int i = 0 ; i < 4 ; i ++ )
for ( int j = 1 ; j <= m; j ++ )
{
if ( ! ok(x + dir[i][ 0 ] * j, y + dir[i][ 1 ] * j))
break ;
if (map[x + dir[i][ 0 ] * j][y + dir[i][ 1 ] * j] > map[x][y])
{
int temp = dfs(x + dir[i][ 0 ] * j, y + dir[i][ 1 ] * j);
if (temp > ans)
ans
= temp;
}
}
f[x][y]
= map[x][y] + ans;
return f[x][y];
}

int main()
{
// freopen("D:\\t.txt", "r", stdin);
while (scanf( " %d%d " , & n, & m) != EOF)
{
if (n == - 1 && m == - 1 )
break ;
input();
memset(f,
- 1 , sizeof (f));
printf(
" %d\n " , dfs( 0 , 0 ));
}
return 0 ;
}

你可能感兴趣的:(OJ)