Find a way
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<cstdio>
#include<cstring>
#include<queue>
using namespace std;
char mp[250][250];
int vis[250][250];//标记该点是否走过
int n,m;
int dx[4]= {1,-1,0,0};
int dy[4]= {0,0,1,-1};
int d[2][250][250];//有两条路,表示起点到每个点的步数,
//这里将起点到每个点的步数都初始化为0,仅存起点到每个@的步数
struct node
{
int x;
int y;
int step;
};
void bfs(int k,int x,int y)
{
memset(vis,0,sizeof(vis));//将标记全部抹去;
queue<node>q;
node first,next;
first.x=x;
first.y=y;
first.step=0;
q.push(first);
vis[x][y]=1;
while(!q.empty())
{
first=q.front();
q.pop();
if(mp[first.x][first.y]=='@')//每出列一个数都判断一下该数是不是@,是则记录步数
d[k][first.x][first.y]=first.step;
for(int i=0; i<4; i++)
{
next.x=first.x+dx[i];
next.y=first.y+dy[i];
if(next.x>=0&&next.x<n&&next.y>=0&&next.y<m&&mp[next.x][next.y]!='#'&&vis[next.x][next.y]==0)
{
vis[next.x][next.y]=1;
next.step=first.step+1;
q.push(next);
}
}
}
}
int main(void)
{
int yx,yy,mx,my;
while(cin>>n>>m)
{
getchar();
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
cin>>mp[i][j];
if(mp[i][j]=='Y')
{
yx=i;
yy=j;
}
if(mp[i][j]=='M')
{
mx=i;
my=j;
}
}
getchar();
}
memset(d,0,sizeof(d));//初始化,多组输入;
bfs(0,yx,yy);
bfs(1,mx,my);
int minn=0x3f3f3f3f;
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
if(mp[i][j]=='@'&&d[0][i][j]!=0&&d[1][i][j]!=0)//如果除掉对d的判断就错了 蒟蒻还没弄明白究竟是为什么 希望能有dalao指教
minn=min(minn,d[0][i][j]+d[1][i][j]);//其实是,比较每一个Y,M到达每一个@总步数,选取最小的
}
cout<<minn*11<<endl;
}
return 0;
}