SYSU暑假热身赛D

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

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

input output
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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值