poj 1383

两次bfs的经典题目

题意:找一棵树中距离最长的两个结点

定理:从任何一个结点出发所到达的最长距离端点一定是最长路径的一个端点

#include <iostream>
#include <vector>
#include <map>
#include <list>
#include <set>
#include <deque>
#include <stack>
#include <queue>
#include <algorithm>
#include <cmath>
#include <cctype>
#include <cstdio>
#include <iomanip>
#include <cmath>
#include <cstdio>
#include <iostream>
#include <string>
#include <sstream>
#include <cstring>
#include <queue>
using namespace std;

///宏定义
const int INF = 20000000;
//const int maxn = 10010;
const int MAXN = 1010;
///全局变量 和 函数
int col, row;
int maze[MAXN][MAXN];
int T;
int dx[] = { -1, 0, 1,  0};
int dy[] = {  0, 1, 0, -1};
char input[MAXN];
int startposRow, startposCol, startposRow1, startposCol1;
int maxlenth;
int color[MAXN][MAXN];
struct pos{
	int row;
	int col;
};
void bfs(int startposRow, int startposCol)
{
	int i, j;
	memset(color, 0, sizeof(color));
	pos tempPos;
	queue<pos> qu;
	int hp = 0, tp = 1, lc = 1;
	tempPos.row = startposRow;
	tempPos.col = startposCol;
	qu.push(tempPos);
	color[tempPos.row][tempPos.col] = 1;
	int level = 0;
	while (!qu.empty())
	{
		tempPos = qu.front();
		qu.pop();
		hp++;

		pos nexspos;
		for (i = 0; i < 4; i++)
		{
			nexspos.row = tempPos.row + dy[i];
			nexspos.col = tempPos.col + dx[i];
			if (nexspos.row >= row || nexspos.col >= col || nexspos.row < 0 || nexspos.col < 0)
				continue;
			if (color[nexspos.row][nexspos.col] == 0 && maze[nexspos.row][nexspos.col] == 1)
			{
				qu.push(nexspos);
				color[nexspos.row][nexspos.col] = 1;
				tp++;
			}
		}
		if (hp == lc)
		{
			lc = tp;
			level++;
			if (level > maxlenth)
			{
				maxlenth = level;
				startposRow1 = tempPos.row;
				startposCol1 = tempPos.col;
			}
		}
	}
}
int main()
{
	///变量定义
	int i, j;
	scanf("%d", &T);
	while (T--)
	{
		scanf("%d%d", &col, &row);
		getchar();
		maxlenth = 0;
		for (i = 0; i < row; i++)
		{
			gets(input);
			for (j = 0; j < col; j++)
			{
				if (input[j] == '#')
					maze[i][j] = 0;
				else
				{
					startposRow = i;
					startposCol = j;
					maze[i][j] = 1;
				}
			}
		}
		bfs(startposRow, startposCol);
		maxlenth = 0;
		bfs(startposRow1, startposCol1);
		printf("Maximum rope length is %d.\n", maxlenth - 1);
	}



	///结束
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值