标签:
Description
Pass a year learning in Hangzhou, yifenfeiarrival hometown Ningbo at finally. Leave Ningbo one year, yifenfei have manypeople to meet. Especially a good friend Merceki.
Yifenfei’s home is at the countryside, butMerceki’s home is in the center of city. So yifenfei made arrangements withMerceki to meet at a KFC. There are many KFC in Ningbo, they want to choose onethat let the total time to it be most smallest.
Now give you a Ningbo map, Both yifenfeiand Merceki can move up, down ,left, right to the adjacent road by cost 11minutes.
Input
The input contains multiple test cases.
Each test case include, first two integersn, m. (2<=n,m<=200).
Next n lines, each line included mcharacter.
‘Y’ express yifenfei initial position.
‘M’ express Merceki initialposition.
‘#’ forbid road;
‘.’ Road.
‘@’ KCF
Output
For each test case output the minimum totaltime that both yifenfei and Merceki to arrival one of KFC.You may sure there isalways 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
题意:yifenfei和Merceki居住在一个城市想要去一家KFC店去玩,求两个人去的KFC的最短距离最短。刚开始想的是设一个家为始点,另一个家为终点,路过的KFC店时,进行标记。后来发现可以从两家搜同一个KFC店,这样把两家到每一KFC的距离存在一个数组里面,输出最短的距离就行了
#include<iostream> #include<stdio.h> #include<queue> #include<string.h> using namespace std; int dx[]={1,0,0,-1}; int dy[]={0,1,-1,0}; int n,m; char mp[250][250]; //输入的数组 int vis[250][250]; //标记数组 int num[250][250]; //存的到每一个KFC店的路径 struct dot { int x,y; int time; }; inline bool in(dot gx) { if(gx.x>=0&&gx.x<n&&gx.y>=0&&gx.y<m) return true; return false; } void bfs(int x,int y) { dot gx; gx.x=x;gx.y=y;gx.time=0; queue<dot> q; while(!q.empty()) q.pop(); q.push(gx); while(!q.empty()) { dot tmp,next; tmp=q.front(),q.pop(); for(int i=0;i<4;i++) { next.x=tmp.x+dx[i]; next.y=tmp.y+dy[i]; next.time=tmp.time+1; if(!vis[next.x][next.y]&&in(next)&&mp[next.x][next.y]!='#') { vis[next.x][next.y]=1; q.push(next); if(mp[next.x][next.y]=='@') num[next.x][next.y]+=next.time; //Y和M遇到同一个KFC店就想加他们的距离 } } } } int main() { int yx,yy,mx,my; while(cin>>n>>m) { for(int i=0;i<n;i++) for(int j=0;j<m;j++) { cin>>mp[i][j]; if(mp[i][j]=='Y') //记录Y的位置 { yx=i; yy=j; vis[i][j]=1; } else if(mp[i][j]=='M') //记录M的位置 { mx=i; my=j; vis[i][j]=1; } } memset(num,0,sizeof(num)); memset(vis,0,sizeof(vis)); bfs(yx,yy); //求Y到KFC的最短距离 memset(vis,0,sizeof(vis)); //这一步很重要应为Y搜过之后就需要把标记数组置为0 bfs(mx,my); //求M到KFC的最短距离 int min=9999999; for(int i=0;i<n;i++) //找出最短的 for(int j=0;j<m;j++) { if(num[i][j]!=0&&min>num[i][j]) { min=num[i][j]; } } printf("%d\n",min*11); } return 0; }
标签:
原文地址:http://blog.csdn.net/qq_qingtian/article/details/45175865