DFS 解 滑雪问题


利用深度优先搜索和存储中间值。

#include <iostream>
#include <string.h>
using namespace std;
int m, n;
int map[101][101];
int opt[101][101]; //存储一些中间结果,防止重复计算
int ans;
int dir[4][2] =
{{ -1, 0 },
{ 0, -1 },
{ 1, 0 },
{ 0, 1 } };
bool check(int x, int y)
{
	return x >= 0 && x < m && y >= 0 && y < n;
}
void f(int x, int y, int len)
{

	if (len > ans)
	{
		ans = len;
	}

	for (int i = 0; i < 4; i++)
	{
		int tempx = x + dir[i][0];
		int tempy = y + dir[i][1];
		if (check(tempx, tempy) && map[tempx][tempy] < map[x][y])
		{
			//如果此位置已经计算出结果,直接加上即可。
			if(opt[tempx][tempy] && opt[tempx][tempy] + len > ans)
				ans = opt[tempx][tempy] + len;
			else
				f(tempx, tempy, len + 1);
		}
	}
}

int main()
{
	while (cin >> m >> n)
	{
		if (m == -1)
			break;
		memset(opt, 0, sizeof(opt));
		for (int i = 0; i < m; i++)
			for (int j = 0; j < n; j++)
				cin >> map[i][j];
		int max = 0;
		for (int i = 0; i < m; i++){
			for (int j = 0; j < n; j++)
			{
				ans = 0;
				f(i,j,1);
				opt[i][j] = ans;
				if(ans > max)
					max = ans;
			}
		}
		cout << max << endl;

}
return 0;
}
测试数据
/*
5 5
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
3 3
9 1 2
5 6 7
8 4 3
*/

25

4

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值