思路:
- 记忆化搜索,注意本代码成立的前提是“He eats up the cheese where he stands and then runs either horizontally or vertically to another location.” 即每次行动时只能选定一个方向猛冲。
代码:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int mt[4][2] = {1,0 , -1,0 , 0,1 , 0,-1};
const int maxn = 105;
int N,K;
int A[maxn][maxn];
int dp[maxn][maxn];
bool CHECK(int x,int y){
if(x>=1 && x<=N && y>=1 && y<=N)
return true;
return false;
}
int dfs(int x,int y){
if(dp[x][y])
return dp[x][y];
int MAX = 0;
for(int i=0;i<4;i++){
for(int j=1;j<=K;j++){
int nx = x + mt[i][0]*j;
int ny = y + mt[i][1]*j;
if(CHECK(nx,ny) && A[nx][ny]>A[x][y])
MAX = max(MAX , dfs(nx,ny));
}
}
return dp[x][y] = MAX + A[x][y];
}
int main(){
while(cin>>N>>K && N != -1){
for(int i=1;i<=N;i++)
for(int j=1;j<=N;j++)
cin>>A[i][j];
memset(dp , 0 , sizeof(dp));
cout<<dfs(1,1)<<endl;
}
return 0;
}