题解:
简单记忆化搜索。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int MAXN=104;
int n,m;
int a[MAXN][MAXN];
int dp[MAXN][MAXN];
int dx[4]={0,0,1,-1},dy[4]={1,-1,0,0};
inline int read() {
int x=0,f=1;char c=getchar();
while (c<'0'||c>'9') {if (c=='-') f=-1;c=getchar();}
while (c>='0'&&c<='9') x=x*10+c-'0',c=getchar();
return x*f;
}
inline bool in(int a,int b) {
return a>0&&a<=n&&b>0&&b<=n;
}
int dfs(int x,int y) {
if (~dp[x][y]) return dp[x][y];
int mx=0;
for (int i=1;i<=m;++i)
for (int j=0;j<4;++j) {
int xx=x+dx[j]*i,yy=y+dy[j]*i;
if (in(xx,yy)&&a[xx][yy]>a[x][y]) mx=max(mx,dfs(xx,yy));
}
return dp[x][y]=mx+a[x][y];
}
int main() {
// freopen("hdu 1078.in","r",stdin);
while (scanf("%d%d",&n,&m)&&~n&&~m) {
memset(dp,-1,sizeof(dp));
for (int i=1;i<=n;++i)
for (int j=1;j<=n;++j)
a[i][j]=read();
printf("%d\n",dfs(1,1));
}
return 0;
}