记忆化搜索即可。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 100 + 10;
const int dx[4] = {-1, 0, 1, 0};
const int dy[4] = {0, -1, 0, 1};
int grid[maxn][maxn];
int dp[maxn][maxn];
int n, k;
int Dfs(int x, int y) {
if (dp[x][y]) {
return dp[x][y];
}
int ans = 0;
for (int i = 1; i <= k; i++) {
for (int d = 0; d < 4; d++) {
int nx = x + dx[d] * i;
int ny = y + dy[d] * i;
if (nx >= 0 && nx < n && ny >= 0 && ny < n && grid[nx][ny] > grid[x][y]) {
ans = max(ans, Dfs(nx, ny));
}
}
}
return dp[x][y] = ans + grid[x][y];
}
int main(int argc, char const *argv[]) {
while (scanf("%d%d", &n, &k) == 2) {
if (n == -1 && k == -1) {
break;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &grid[i][j]);
}
}
memset(dp, 0, sizeof(dp));
printf("%d\n", Dfs(0, 0));
}
return 0;
}