hdu Find a way

算法:广搜;

Description
Pass a year learning in Hangzhou, yifenfei arrival hometown Ningbo at finally. Leave Ningbo one year, yifenfei have many people to meet. Especially a good friend Merceki.
Yifenfei’s home is at the countryside, but Merceki’s home is in the center of city. So yifenfei made arrangements with Merceki to meet at a KFC. There are many KFC in Ningbo, they want to choose one that let the total time to it be most smallest.
Now give you a Ningbo map, Both yifenfei and Merceki can move up, down ,left, right to the adjacent road by cost 11 minutes.

Input
The input contains multiple test cases.
Each test case include, first two integers n, m. (2<=n,m<=200).
Next n lines, each line included m character.
‘Y’ express yifenfei initial position.
‘M’ express Merceki initial position.
‘#’ forbid road;
‘.’ Road.
‘@’ KCF

Output
For each test case output the minimum total time that both yifenfei and Merceki to arrival one of KFC.You may sure there is always have a KFC that can let them meet.

Sample Input
4 4
Y.#@
....
.#..
@..M
4 4
Y.#@
....
.#..
@#.M
5 5
Y..@.
.#...
.#...
@..M.
#...#



Sample Output
66
88
66

啥也不说了直接代码

代码:

#include <iostream>
#include <string>
#include <cstring>
#include <iomanip>
#include <algorithm>
#include <queue>
using namespace std;
#define INF 10000000
int n,m,c[205][205],g[4][2]={-1,0,1,0,0,-1,0,1},e[205][205],a[205][205],b[205][205];
char ch[205][205];
struct dot
{
	int x, y;
} ;
void bfs(int dx,int dy,int k)
{   memset(e,0,sizeof(e));
	queue<dot>que;
	dot cur,loer;
	cur.x=dx;cur.y=dy;
	if(k==0)a[dx][dy]=0;
	else b[dx][dy]=0;
	que.push(cur);
	while(que.size())
	{  
		loer=que.front();
		que.pop();
		for(int i=0;i<4;i++)
		{
			int nx=loer.x+g[i][0];
			int ny=loer.y+g[i][1];
			if(nx>=0&&nx<n&&ny>=0&&ny<m&&ch[nx][ny]!='#'&&!e[nx][ny])
			{
				if(k==0)a[nx][ny]=a[loer.x][loer.y]+1;
				else if(k==1)b[nx][ny]=b[loer.x][loer.y]+1;
				cur.x=nx;
				cur.y=ny;
				e[nx][ny]=1;
				que.push(cur);
			}
		}
	}
}
int main()
{
	int i,j,k,p,q,s,t;
	while(cin>>n>>m)
	{
		for(i=0;i<n;i++)
		{
			for(j=0;j<m;j++)
			{
				cin>>ch[i][j];
				a[i][j]=b[i][j]=INF;
				if(ch[i][j]=='Y')
				{
					s=i;t=j;ch[i][j]='#';
				}
				else if(ch[i][j]=='M')
				{
					p=i;q=j;ch[i][j]='#';
				}
			}
		}
		bfs(s,t,0);
		bfs(p,q,1);
		int Mx=10000000;
		for(i=0;i<n;i++)
		{
			for(j=0;j<m;j++)
			{
				if(ch[i][j]=='@')
				{
					if(Mx>a[i][j]+b[i][j])
					Mx=a[i][j]+b[i][j];
				}
			}
		}
		cout<<11*Mx<<endl;
	}
	return 0;
 } 


posted @ 2016-01-02 20:40  (慎独)  阅读(187)  评论(0编辑  收藏  举报