典型的bfs我还做了这么半天。。。
注意:本题是强制转换!!!
#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
struct node
{
int x1,x2,y1,y2;
}edge[30];
int dir[4][2]={
1,0,
0,1,
-1,0,
0,-1
};
int n,m;
char map[500][500];
int sx,sy,tx,ty;
int dis[500][500];
int tox[500][500],toy[500][500];
int vis[500][500];
int inside(int x,int y)
{
if(x>=0&&x<n&&y>=0&&y<m)return 1;
return 0;
}
int bfs()
{
memset(dis,0x3f,sizeof(dis));
queue<int>X;
queue<int>Y;
X.push(sx);
Y.push(sy);
dis[sx][sy]=0;
vis[sx][sy]=1;
while(!X.empty())
{
int ux=X.front();
int uy=Y.front();
X.pop();
Y.pop();
vis[ux][uy]=0;
if(ux==tx&&uy==ty)
{
return dis[ux][uy];
}
for(int i=0;i<4;i++)
{
int vx=ux+dir[i][0];
int vy=uy+dir[i][1];
if(inside(vx,vy)==0)continue;
if(map[vx][vy]=='.'||map[vx][vy]=='=')
{
if(dis[vx][vy]>dis[ux][uy]+1)
{
dis[vx][vy]=dis[ux][uy]+1;
X.push(vx);
Y.push(vy);
}
}else if(map[vx][vy]>='A'&&map[vx][vy]<='Z')
{
if(dis[tox[vx][vy]][toy[vx][vy]]>dis[ux][uy]+1)//直接跳到另一点,这一点不算。
{
dis[tox[vx][vy]][toy[vx][vy]]=dis[ux][uy]+1;
if(vis[tox[vx][vy]][toy[vx][vy]]==0)
{
vis[tox[vx][vy]][toy[vx][vy]]=1;
X.push(tox[vx][vy]);
Y.push(toy[vx][vy]);
}
}
}
}
}
return 0;
}
int main()
{
memset(edge,-1,sizeof(edge));
scanf("%d %d",&n,&m);
for(int i=0;i<n;i++)
{
scanf("%s",map[i]);
for(int j=0;j<m;j++)
{
if(map[i][j]=='=')
{
tx=i;
ty=j;
}else if(map[i][j]=='@')
{
sx=i;
sy=j;
}else if(map[i][j]>='A'&&map[i][j]<='Z')
{
int t=map[i][j]-'A';
if(edge[t].x1==-1)
{
edge[t].x1=i;
edge[t].y1=j;
}else
{
edge[t].x2=i;
edge[t].y2=j;
tox[edge[t].x1][edge[t].y1]=edge[t].x2;
toy[edge[t].x1][edge[t].y1]=edge[t].y2;
tox[edge[t].x2][edge[t].y2]=edge[t].x1;
toy[edge[t].x2][edge[t].y2]=edge[t].y1;
}
}
}
}
printf("%d",bfs());
}