这是在自己学习完搜素自己亲自写的一道题, 原先觉得搜索题好蛮烦的饿现在觉得还行, 原来也是很简单的,有时候这些算法这些东西是靠时间来慢慢悟的,当然必须的用几道题来锻炼自己一下,这道题没有什么太大的难点,就是在广搜的时候有两种方法 首先是从两个人的起始位置开是搜索这样搜索的时间最短但是得用两个数组cnt和cnt1来记录到达每一个点的位置,还有就是从每个bfc的点来搜,这样搜索的时间会很长,我第一次写就是这么搜索的,理解错题了竟然;
这道题的题意就是有两个人S和Y,他们想约会,问附近的那个BFC让他们俩到的距离之和最短。其中S和Y表两个人, “.” 表示道路 “@”表示bfc;
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<iostream>
#include<algorithm>
#include<queue>
#define maxn 50000
using namespace std;
int n, m, s1,s2,e1,e2, k;///定义的两个人所在的位置
int num[maxn][2], v[205][205];///num是记录bfc所在的位置,v是广搜的标记数组
char mapp[205][205];
int to[4][2]={{1,0},{-1,0},{0,1},{0,-1}};///上下左右四个方向
void bfs(int x, int y,int cnt[205][205])
{
queue<node> q;
node a, c;
int i;
a.x=x;
a.y=y;
q.push(a);
while(!q.empty())
{
c=q.front();
q.pop();
for(i=0;i<4;i++)
{
int X=c.x+to[i][0];
int Y=c.y+to[i][1];
if(X>=0 && X<n && Y>=0 && Y<m && !v[X][Y] && mapp[X][Y]!='#')///判断是否符合要求
{
a.x=X; a.y=Y; cnt[X][Y]=cnt[c.x][c.y]+1;
v[X][Y]=1;
q.push(a);
}
}
}
}
int main()
{
int i, j, ans, Min;
int cnt[205][205], cnt1[205][205];
while(scanf("%d%d",&n, &m)!=EOF)
{
memset(mapp,0,sizeof(mapp));
k=0;
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
cin>>mapp[i][j];
if(mapp[i][j]=='Y')
{
s1=i,e1=j;
}
if(mapp[i][j]=='M')
{
s2=i;e2=j;
}
if(mapp[i][j]=='@')
{
num[k][0]=i;
num[k][1]=j;
k++;
}
}
}
memset(cnt,0,sizeof(cnt));
memset(v,0,sizeof(v));
v[s1][e1]=1;
bfs(s1,e1,cnt);
memset(v,0,sizeof(v));
memset(cnt1,0,sizeof(cnt1));
v[s2][e2]=1;
cnt1[s2][e2]=0;
bfs(s2,e2,cnt1);
Min=9999999;
for(i=0;i<k;i++)
{
int x=num[i][0];
int y=num[i][1];
if(cnt1[x][y] && cnt[x][y])
if(cnt[x][y]+cnt1[x][y]<Min)
Min=cnt[x][y]+cnt1[x][y];
}
printf("%d\n",Min*11);
}
}