| input | output | 
|---|---|
7 6 ####### #.#.### #.#.### #.#.#.# #.....# #######  | 
8  | 
首先我们要知道怎么求树的直径。
树的直径是指树的最长简单路。
求法: 两遍BFS :先任选一个起点BFS找到最长路的终点,再从终点进行BFS,则第二次BFS找到的最长路即为树的直径;
题意:给了个图,‘ . ‘ 可以走 ‘ # ’ 是墙。因为题目中规定了两点之间最多只有一条路可以走,而且必有一条路。可以见‘ . ’ 是一个树的结构。要求得距离最长的两点的距离。也就是求树的直径了。
做法: 找到节点,节点就是三面有‘ # ‘ 的 点。然后bfs 两遍求出直径就可以了。
注意:图很大,dfs 会超内存。
#include<stdio.h>
#include<iostream>
#include<string>
#include<map>
#include<queue>
using namespace std;
int dir[4][2]={1,0,-1,0,0,1,0,-1};
char mp[830][830]; 
int ans;
int n,m;
int bix;
int biy;
int pp;
struct nodes
{
	int x,y,num,ff;
};
nodes now,tem;
bool ok(int a,int b)
{
    if(a==0&&b==1)
        return 0;
    if(a==1&&b==0)
        return 0;
    if(a==2&&b==3)
        return 0;
    if(a==3&&b==2)
        return 0;
    return 1;
}
void bfs(int x,int y)
{
	queue<nodes>q;
	now.ff=-1;
	now.num=0;
	now.x=x;
	now.y=y;
	q.push(now);
	while(!q.empty())
	{
		now=q.front();
		q.pop();
		if(now.num>ans)
		{
			bix=now.x;
			biy=now.y;
			ans=now.num;
		}
		int xx,yy;
		for(int i=0;i<4;i++)
		{
			xx=now.x+dir[i][0];
			yy=now.y+dir[i][1];
			if(xx>=0&&xx<n&&yy>=0&&yy<m&&mp[xx][yy]=='.'&&ok(i,now.ff))
			{
				tem.x=xx;
				tem.y=yy;
				tem.num=now.num+1;
				tem.ff=i;
				q.push(tem);
			}
		} 
	} 
}
int main()
{
	while(scanf("%d%d",&m,&n)!=EOF)
	{
	    ans=0;
	    for(int i=0;i<n;i++)//mp[n][m]
            scanf("%s",mp[i]);
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                if(mp[i][j]=='.')
                {
                    int num=0;
                    for(int k=0;k<4;k++)
                    {
                        int xx=i+dir[k][0];
                        int yy=j+dir[k][1];
                        if(xx>=0&&xx<n&&yy>=0&&yy<m)
                        {
                            if(mp[xx][yy]=='.')
                                num++;
                        }
                    } 
					if(num==1)
						pp=i*m+j;
                }
			}
		} 
		bfs(pp/m,pp%m);  
		bfs(bix,biy);
        printf("%d\n",ans);
	}
	return 0;
}
ural 1145 Rope in the Labyrinth 图中 bfs求树的直径
原文地址:http://blog.csdn.net/u013532224/article/details/43760039