hdu 2216 bfs

时间:2023-03-08 22:15:05

题目大意:两个东西朝相同方向移动
Sample Input
4 4
XXXX
.Z..
.XS.
XXXX
4 4
XXXX
.Z..
.X.S
XXXX
4 4
XXXX
.ZX.
.XS.
XXXX
Sample Output
1
1
Bad Luck!

由于两个棋子必然有一个移动。所以假设其中一个一直移动即可,比较水了

 #include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
using namespace std;
int n,m,t;
int d1[][]={,,,,-,,,-};
int d2[][]={-,,,-,,,,};
char s[][];
int vis[][][][];
struct node
{
int x1,y1,s,x2,y2;
node(){}
node(int xx,int yy,int xxx,int yyy,int ss)
{
x1=xx;y1=yy;x2=xxx;y2=yyy;s=ss;
}
}st,ed;
void bfs()
{
queue<node> q;
node now,next;
while(!q.empty()) q.pop();
q.push(node(st.x1,st.y1,st.x2,st.y2,));
while(!q.empty())
{
now=q.front();
q.pop();
//printf("%d %d %d %d %d\n",now.x1,now.y1,now.x2,now.y2,now.s);
if(fabs(now.x1-now.x2)+fabs(now.y1-now.y2)<)
{
printf("%d\n",now.s);
return;
}
for(int i=;i<;i++) //肯定有一个棋子是移动的,以这个棋子作为判断依据
{
next.x1=now.x1+d1[i][];
next.y1=now.y1+d1[i][];
next.x2=now.x2+d2[i][];
next.y2=now.y2+d2[i][];
if(next.x1<||next.x1>=n||next.y1<||next.y1>=m||s[next.x1][next.y1]=='X') continue; //这棋子必须移动
if(next.x2<||next.x2>=n||next.y2<||next.y2>=m||s[next.x2][next.y2]=='X')
{
next.x2=now.x2,next.y2=now.y2;
}
if(vis[next.x1][next.y1][next.x2][next.y2]) continue;
vis[next.x1][next.y1][next.x2][next.y2]=;
next.s=now.s+;
q.push(next);
}
}
printf("Bad Luck!\n");
}
int main()
{
int i,j,k;
freopen("1.in","r",stdin);
while(scanf("%d%d",&n,&m)!=EOF)
{
for(i=;i<n;i++)
{
scanf("%s",s[i]);
for(j=;j<m;j++)
{
if(s[i][j]=='Z') st.x1=i,st.y1=j;
if(s[i][j]=='S') st.x2=i,st.y2=j;
}
}
memset(vis,,sizeof(vis));
bfs();
}
return ;
}