L - Find a way
Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
Submit
Status
Practice
HDU 2612
Appoint description:
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
题意:多组数据,每组数据给出N和M,代表下面要输入N*M的图。图中有Y和M的坐标,有很多个@,求Y和M到同一个@的最短时间,注意@是可以当做通路的!!
思路:存图时记下Y和M坐标,然后作为起点,暴搜全图,遇到@就记下起点到@的距离。
这样两边暴搜就能得到答案,中间有很多细节需要注意。
代码
#include<stdio.h>
#include<algorithm>
#include<iostream>
#include<string.h>
#include<queue>
#include<math.h>
using namespace std;
const int maxn=205;
const int INF=0x3f3f3f3f;
char map[maxn][maxn];
int vis[maxn][maxn];
int dis[4][2]= {{0,-1},{0,1},{1,0},{-1,0}};
struct node
{
int x;
int y;
int steap;
};
struct edge
{
int num;//记录步数
int flag;//记录到达人数,只有两人都到达,步数才有效
} num[maxn][maxn];
int N;
int M;
int point_x_Y;
int point_y_Y;
int point_x_M;
int point_Y_M;
void init()
{
for(int i=0; i<N; i++)
{
for(int j=0; j<M; j++)
{
cin>>map[i][j];
if(map[i][j]=='Y')
{
point_x_Y=i;
point_y_Y=j;
}
else if(map[i][j]=='M')
{
point_x_M=i;
point_Y_M=j;
}
num[i][j].flag=0;//初始化记录步数的数组
num[i][j].num=0;
}
}
}
bool Judge(int x,int y)
{
if(x>=0&&x<N&&y>=0&&y<M&&map[x][y]!='#'&&vis[x][y]==0)//KFC也是路
return true;
return false;
}
void BFS(int star_x,int star_y)
{
memset(vis,0,sizeof(vis));
vis[star_x][star_y]=1;
node star;
star.x=star_x;
star.y=star_y;
star.steap=0;
queue<node>q;
q.push(star);
while(!q.empty())
{
star=q.front();
q.pop();
if(map[star.x][star.y]=='@')
{
num[star.x][star.y].num+=star.steap;
num[star.x][star.y].flag++;
}
for(int i=0; i<4; i++)
{
node end=star;
end.x+=dis[i][0];
end.y+=dis[i][1];
end.steap++;
if(Judge(end.x,end.y))
{
vis[end.x][end.y]=1;
q.push(end);
}
}
}
}
int main()
{
while(~scanf("%d%d",&N,&M)&&N&&M)
{
init();
BFS(point_x_M,point_Y_M);
BFS(point_x_Y,point_y_Y);
//接着遍历num找最小时间
int min_time=INF;
for(int i=0; i<N; i++)
for(int j=0; j<M; j++)
if(map[i][j]=='@'&&num[i][j].flag==2&&num[i][j].num<min_time)
min_time=num[i][j].num;
printf("%d\n",min_time*11);
}
return 0;
}