题意:
一张n*n的格子表格,每个格子里有个数,每次能够水平或竖直走k个格子,允许上下左右走,每次走的格子上的数必须比上一个走的格子的数大,问最大的路径和。
记忆化搜索
#include <iostream> #include <string.h> #include <stdio.h> using namespace std; int dir[4][2] = { {1,0 },{ -1, 0}, {0, 1}, {0, -1} }; int dp[105][105]; int m[105][105]; int n, k; int dfs(int x,int y) { int max = 0; if (!dp[x][y]) { for (int i = 1; i <= k; i++) { for (int j = 0; j < 4; j++) { int tox = x + i * dir[j][0], toy = y + i * dir[j][1]; if (tox >= 0 && tox <= n - 1 && toy >= 0 && toy <= n - 1) { if (m[tox][toy] > m[x][y]) { int t = dfs(tox, toy); max = t > max ? t : max; } } } } dp[x][y] = max + m[x][y]; } return dp[x][y]; } int main() { while(scanf("%d%d", &n, &k) != EOF && (n != -1 || k != -1)){ memset(dp, 0, sizeof(dp)); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { scanf("%d", &m[i][j]); } } cout << dfs(0, 0) << endl; } return 0; }