题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1078
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
using namespace std;
const int maxn=100+5;
int N,k;
int G[maxn][maxn],d[maxn][maxn];
const int dx[]={1,-1,0,0};
const int dy[]={0,0,1,-1};
bool inside(int x,int y){
return x>=0&&x<N&&y>=0&&y<N;
}
int DP(int x,int y){
int& ans=d[x][y];
if(ans!=0) return ans;
for(int i=1;i<=k;i++)
for(int j=0;j<4;j++){
int nx=x+i*dx[j];
int ny=y+i*dy[j];
if(inside(nx,ny)&&G[nx][ny]>G[x][y])
ans=max(ans,DP(nx,ny));
}
ans+=G[x][y];
return ans;
}
int main()
{
while(cin>>N>>k)
{
if(k==-1&&N==-1) break;
for (int i = 0; i < N; ++i)
for (int j = 0; j < N; ++j)
scanf("%d",&G[i][j]);
memset(d,0,sizeof(d));
cout<<DP(0,0)<<endl;
}
return 0;
}