记忆化搜索模板

#include 
#include 
#include 
using namespace std;
int max(int a, int b) {
	if (a > b)return a;
	else return b;
}

int n;
int k;


int maze[105][105];
int dx[4] = { 0,0,1,-1 };
int dy[4] = { 1,-1,0,0 };

int dp[105][105];

int dfs(int x, int y) {
	int Max = 0;
	for (int i = 1; i <= k; i++) {
		for (int j = 0; j < 4; j++) {
			int x1 = x + dx[j] * i;
			int y1 = y + dy[j] * i;


			if (x1 < 0|| y1 < 0|| x1 >= n|| y1 >= n|| maze[x][y] >= maze[x1][y1]) continue;//////ccccccccccccccccc


			if (dp[x1][y1]) { 
				Max = max(Max, dp[x1][y1]); 
				continue;
			}
			Max = max(Max, dfs(x1, y1)); 
		}
	}
	dp[x][y] = Max + maze[x][y];
	return dp[x][y];
}

int main() {

	while (cin >> n >> k && n > 0 && k > 0) {
		memset(dp,0,sizeof(dp));
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				cin >> maze[i][j];
			}
		}

		cout << dfs(0, 0)<<endl;
	}
	return 0;
}

你可能感兴趣的:(记忆化搜索)