您的位置:首页 > 其它

hdu 2612 Find a way【BFS】

2017-02-17 14:20 357 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2612

题意:y和m要在kfc见面,问你能否选择一家kfc使得y和m到那里的距离最短

解析:两个人都跑一遍bfs,然后枚举每家kfc,找出最优的即可

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;
const int inf = 0x7fffffff;
int dx[] = {0,1,-1,0};
int dy[] = {1,0,0,-1};
int vis[205][205];
int step1[205][205];
int step2[205][205];
int n,m;
char a[205][205];
struct node
{
int x,y;
int step;
node() {}
node(int _x,int _y,int _step)
{
x = _x;
y = _y;
step = _step;
}
};
void bfs(int sx,int sy,int step[205][205])
{
memset(vis,0,sizeof(vis));
queue<node>q;
q.push(node(sx,sy,0));
while(!q.empty())
{
node now = q.front();
q.pop();
if(a[now.x][now.y]=='@')
{
if(step[now.x][now.y])
step[now.x][now.y] = min(step[now.x][now.y],now.step);
else
step[now.x][now.y] = now.step;
}
for(int i=0;i<4;i++)
{
int tx = now.x+dx[i];
int ty = now.y+dy[i];
if(tx<0 || tx>=n || ty<0 || ty>=m)
continue;
if(a[tx][ty]=='#' || vis[tx][ty])
continue;
vis[tx][ty] = 1;
q.push(node(tx,ty,now.step+1));
}
}
}
int main()
{
while(~scanf("%d %d",&n,&m))
{
int x1,y1,x2,y2;
for(int i=0;i<n;i++)
{
scanf("%s",a[i]);
for(int j=0;j<m;j++)
{
if(a[i][j]=='Y')
{
x1 = i;
y1 = j;
}
if(a[i][j]=='M')
{
x2 = i;
y2 = j;
}
}
}
memset(step1,0,sizeof(step1));
memset(step2,0,sizeof(step2));
bfs(x1,y1,step1);
bfs(x2,y2,step2);
int ans = inf;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(a[i][j] == '@')
{
if(step1[i][j] && step2[i][j])
ans = min(ans,step1[i][j]+step2[i][j]);
}
}
}
printf("%d\n",ans*11);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: