首页 > 代码库 > SYSU暑假热身赛D

SYSU暑假热身赛D

D - Rope in the Labyrinth
Time Limit:500MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u
Submit Status Practice URAL 1145

Description

A labyrinth with rectangular form and size m × n is divided into square cells with sides‘ length 1 by lines that are parallel with the labyrinth‘s sides. Each cell of the grid is either occupied or free. It is possible to move from one free cell to another free cells that share a common side with the cell. One cannot move beyond the labyrinth‘s borders. The labyrinth is designed pretty specially: for any two cells there is only one way to move from one cell to the other. There is a hook at each cell‘s center. In the labyrinth there are two special free cells, such that if you can connect the hooks of those two cells with a rope, the labyrinth‘s secret door will be automatically opened. The problem is to prepare a shortest rope that can guarantee, you always can connect the hooks of those two cells with the prepared rope regardless their position in the labyrinth.

Input

The first line contains integers n and m (3 ≤ nm ≤ 820). The next lines describe the labyrinth. Each of the next m lines contains ncharacters. Each character is either "#" or ".", with "#" indicating an occupied cell, and "." indicating a free cell.

Output

Print out in the single line the length (measured in the number of cells) of the required rope.

Sample Input

inputoutput
7 6
#######
#.#.###
#.#.###
#.#.#.#
#.....#
#######
8
                                     
解题思路:两遍BFS求树的直径
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
#define Inf 0x7fffffff
using namespace std;
char maze[850][850];
int mov[4][2]={0,1,0,-1,1,0,-1,0};
struct node
{
	int x,y;
	int step;
};
bool vis[850][850];
node bfs(int a,int b)
{
	int i,x,y;
    memset(vis,false,sizeof(vis));
    node ans;
    ans.x=a,ans.y=b,ans.step=0;
	node ini;
	ini.x=a,ini.y=b,ini.step=0;
	queue<node> q;
	q.push(ini);
	vis[a][b]=true;
	while(!q.empty())
	{
		ini=q.front();
		q.pop();
		if(ans.step<ini.step)
			ans=ini;
		for(int i=0;i<4;i++)
		{
			int x=ini.x+mov[i][0];
			int y=ini.y+mov[i][1];
			int s=ini.step+1;
			node tmp;tmp.x=x;tmp.y=y;tmp.step=s;
			if(!vis[x][y]&&maze[x][y]!='#')
			{
				vis[x][y]=true;
				q.push(tmp);
			}
		}
	}
	return ans;
}
int main()
{
	int m,n,a,b;
	//freopen("in.txt","r",stdin);
	//freopen("out.txt","w",stdout);
	while(~scanf("%d %d\n",&m,&n))
	{
		memset(maze,'#',sizeof(maze));
		for(int i=1;i<=n;i++)
		{
			for(int j=1;j<=m;j++)
			{
				scanf("%c",&maze[i][j]);
				if(maze[i][j]=='.')
					a=i,b=j;
			}
			getchar();
		}
		node p1=bfs(a,b);
		node p2=bfs(p1.x,p1.y);
		//cout<<p2.x<<" "<<p2.y<<endl;
		printf("%d\n",p2.step);
	}
	return 0;
}