两次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;
}