Problem 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
题意:
给你个图,有两个起点与若干个终点,问两起点到同一终点的最短距离。
思路:
寻求最短路,用BFS即可,由于有两个起点,所以需要获取起点坐标进行两次BFS。
代码:
#include<iostream>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
char map[210][210];
int vis[210][210];
int n,m,out1;
struct node{
int x,y,step;
}out[100],y1,m1;
bool myfunc(node x,node y){
if(x.x==y.x) return x.y<y.y;
else return x.x<y.y;
}
bool check(int x,int y){
if(x>=n||x<0||y>=m||y<0||vis[x][y]||map[x][y]=='#') return false;
return true;
}
int step1[210][210],step2[210][210];
void bfs(node st,int step[][210]){
queue<node>q;
q.push(st);
while(!q.empty()){
node temp,ed=q.front();
if(map[ed.x][ed.y]=='@'){
step[ed.x][ed.y]=ed.step;
}
if(check((ed.x)+1,ed.y)){
temp.x=ed.x+1;
temp.y=ed.y;
vis[temp.x][temp.y]=1;
temp.step=ed.step+1;
q.push(temp);
}
if(check(ed.x,ed.y+1)){
temp.x=ed.x;
temp.y=ed.y+1;
vis[temp.x][temp.y]=1;
temp.step=ed.step+1;
q.push(temp);
}
if(check(ed.x-1,ed.y)){
temp.x=ed.x-1;
temp.y=ed.y;
vis[temp.x][temp.y]=1;
temp.step=ed.step+1;
q.push(temp);
}
if(check(ed.x,ed.y-1)){
temp.x=ed.x;
temp.y=ed.y-1;
vis[temp.x][temp.y]=1;
temp.step=ed.step+1;
q.push(temp);
}
q.pop();
}
}
int main(){
while(cin>>n>>m){
memset(map,0,sizeof(map));
memset(vis,0,sizeof(vis));
memset(out,0,sizeof(out)); //初始化
out1=0;
for(int i=0;i<n;i++){
cin>>map[i];
} //输入
for(int i=0;i<n;i++)
for(int j=0;j<m;j++){
if(map[i][j]=='Y'){
y1.x=i;y1.y=j; //获取起点1
}
if(map[i][j]=='M'){
m1.x=i;m1.y=j; //获取起点2
}
}
bfs(y1,step1); //通过step数组来存储两个起点分别的路径数
memset(vis,0,sizeof(vis));
bfs(m1,step2);
int MAXT=1e6;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
if(map[i][j]=='@'&&step1[i][j]!=0&&step2[i][j]!=0)
if(step1[i][j]+step2[i][j]<MAXT) MAXT=step1[i][j]+step2[i][j];
cout<<MAXT*11<<endl;
}
}