POJ1383 Labyrinth(树的直径:两次BFS)

34 篇文章 0 订阅

题意:

给一个迷宫,要求迷宫中最长的路径(就是两点之间的距离最大)

要点:

树的直径问题,有两种方法:第一种就是两次BFS:先以任意点搜索一次找到最长段的一端v,再以v搜索找到最长段的另一端w,第二次搜索出的就是最长路径。第二种就是DP,用记忆化搜索应该可以写,以后再说。


15566071Seasonal1383Accepted5128K719MSC++1157B2016-05-29 09:33:38
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<queue>
using namespace std;
char map[1005][1005];
int dx[4] = { 0,0,1,-1 };
int dy[4] = { 1,-1,0,0 };
int d[1005][1005];
int col, row,fx,fy;

int bfs(int x,int y)
{
	int ans = 0;
	memset(d, -1, sizeof(d));
	queue<int> que;
	que.push(x);
	que.push(y);
	d[x][y] = 0;
	while (!que.empty())
	{
		x = que.front(); que.pop();
		y = que.front(); que.pop();
		for (int i = 0; i < 4; i++)
		{
			int xx = x + dx[i];
			int yy = y + dy[i];
			if (d[xx][yy]==-1 && map[xx][yy]=='.' && xx >= 1 && xx <= row&&yy >= 1 && yy <= col)
			{
				que.push(xx);
				que.push(yy);
				d[xx][yy] = d[x][y] + 1;
				if (ans < d[xx][yy])//记录最长的位置
				{
					ans = d[xx][yy];
					fx = xx;
					fy = yy;
				}
			}
		}
	}
	return ans;
}

int main()
{
	int t,i,j;
	scanf("%d", &t);
	while (t--)
	{
		scanf("%d%d", &col, &row);
		for (i = 1; i <= row; i++)
			scanf("%s", map[i] + 1);
		for (i = 1; i <= row; i++)
			for (j = 1; j <= col; j++)
				if (map[i][j] == '.')
				{
					fx = i;
					fy = j;
					break;
				}
		int ans;
		bfs(fx, fy);		//先以任意点搜索一次找到最长段的一端v
		ans = bfs(fx, fy);	//再以v搜索找到最长段的另一端w
		printf("Maximum rope length is %d.\n", ans);
	}
	return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值