寻宝路线(动态规划)_#define



#include <stdio.h>
#define MAX 101
int map[MAX][MAX];
int S[MAX][MAX];
int F[MAX][MAX];

int m, n;
int max(int a, int b)
{
	return a > b ? a : b;
}
int dp(int i, int j)
{
	if (i < 0 || j < 0)	return -10000;
	if (F[i][j])	return F[i][j]; // F[i][j]存放的就是从右下角到达该点捡起宝物价值最大值,最后F[0][0]即为所求
	if (i == m - 1 && j == n - 1)//ij条件交集放前面 
	{
		return F[i][j] = map[i][j];
	}
	else if (i == m - 1) // 到达底端,就只能往右走
	{
		return F[i][j] = map[i][j] + dp(i, j + 1);
	}
	else if (j == n - 1) // 到达右端,只能往下走
	{
		return F[i][j] = map[i][j] + dp(i + 1, j);
	}
	else // 否则在这一点能够获得的最大价值就是该点的宝物价值加上往右或者往下走能够获得的最大价值
	{
		return F[i][j] = map[i][j] + max(dp(i + 1, j), dp(i, j + 1));
	}
}

int s(int i, int j)
{
	if (i < 0 || j < 0)	return -10000;
	if (S[i][j])	return S[i][j];
	if (i == m - 1 || j == n - 1)//到边界,只能往右或者往下,只有唯一路径,不用继续走了 
	{
		return S[i][j] = 1;
	}
	else
	{
		if (F[i][j] == map[i][j] + F[i][j + 1])	S[i][j] += s(i, j + 1);
		if (F[i][j] == map[i][j] + F[i + 1][j])	S[i][j] += s(i + 1, j);
		return S[i][j];
	}
}

int main()
{
	int i, j;
	scanf("%d %d", &m, &n);
	for (i = 0; i < m; ++i)
	{
		for (j = 0; j < n; ++j)
		{
			scanf("%d", &map[i][j]);
		}
	}
	printf("%d ", dp(0, 0));

  /*putchar('\n');
	putchar('\n');
	printf("便于理解,打印F数组,记录最值:\n");
	for (i = 0; i < m; ++i)
	{
		for (j = 0; j < n; ++j)
		{
			printf("%d ", F[i][j]);
		}
		putchar('\n');
	}
	putchar('\n');
	putchar('\n');*/

	printf("%d\n",s(0,0));

	/*putchar('\n');
	putchar('\n');
	printf("便于理解,打印S数组,记录路径最大值:\n");
	for (i = 0; i < m; ++i)
	{
		for (j = 0; j < n; ++j)
		{
			printf("%d ", S[i][j]);
		}
		putchar('\n');
	}*/

	return 0;
}

相似的题目,贪心加动态规划,见我另一篇博客

点击打开链接



========================================Talk is cheap, show me the code=======================================