HDU - 2612 Find a way 【双向bfs】
题目简述
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.
输入
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
输出
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.
分析
分别对两个人的位置跑一边bfs,一旦交汇到KFC处就更新一下答案。
与传统双向bfs不同的地方是需要更新最小路径。
AC代码:
点击查看代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
using namespace std;
#define N 205
#define inf 1145141919
struct node{
int x,y,id;
}s,r;
const int dx[]={-1,0,0,1};
const int dy[]={0,-1,1,0};
int dis1[N][N],dis2[N][N];
char ch[N][N];
int ans=inf,n,m;
void bfs(){
queue<node>q;
q.push(s);q.push(r);
while(!q.empty()){
node temp=q.front();q.pop();
int tempx=temp.x,tempy=temp.y;
if(dis1[tempx][tempy]&&dis2[tempx][tempy]&&ch[tempx][tempy]=='@'){
ans=min(ans,dis1[tempx][tempy]+dis2[tempx][tempy]);
}
for(int i=0;i<=3;i++){
int nx=tempx+dx[i],ny=tempy+dy[i],id=temp.id;
if(id==1){
if(nx<=0 || nx>n || ny<=0 || ny>m|| ch[nx][ny]=='#'|| dis1[nx][ny]) continue;
node curr;curr.id=id;curr.x=nx;curr.y=ny;
q.push(curr);
dis1[curr.x][curr.y]=dis1[tempx][tempy]+1;
}
else if(id==2){
if(nx<=0 || nx>n || ny<=0 || ny>m|| ch[nx][ny]=='#'|| dis2[nx][ny]) continue;
node curr;curr.id=id;curr.x=nx;curr.y=ny;
q.push(curr);
dis2[curr.x][curr.y]=dis2[tempx][tempy]+1;
}
}
}
}
int main(){
while(cin>>n>>m){
ans=inf;
memset(dis1,0,sizeof(dis1));
memset(dis2,0,sizeof(dis2));
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++){
cin>>ch[i][j];
if(ch[i][j]=='Y'){
s.id=1;s.x=i;s.y=j;
}
if(ch[i][j]=='M'){
r.id=2;r.x=i;r.y=j;
}
}
bfs();
cout<<11*ans<<endl;
}
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!