模板 BFS

时间:2023-03-09 21:35:01
模板 BFS

【模板】BFS

 #include <stdio.h>
#include <string.h>
#include <queue>
using namespace std; struct node
{
int x,y,step;
}; char map[][];
int vis[][];
int to[][]= {,,-,,,,,-};
int n,m,sx,sy,ex,ey,ans; int check(int x,int y)
{
if(x< || x>=n || y< || y>=m)
return ;
if(vis[x][y] || map[x][y]=='#')
return ;
return ;
} void bfs()
{
int i;
queue<node> Q;
node a,next;
a.x = sx;
a.y = sy;
a.step = ;
vis[a.x][a.y]=;
Q.push(a);
while(!Q.empty())
{
a = Q.front();
Q.pop();
if(map[a.x][a.y]=='E')
{
ans = a.step;
return ;
}
for(i = ; i<; i++)
{
next = a;
next.x+=to[i][];
next.y+=to[i][];
if(check(next.x,next.y))
continue;
next.step=a.step+;
vis[next.x][next.y] = ;
Q.push(next);
}
}
ans = -;
} int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
int i,j;
for(i = ; i<n; i++)
scanf("%s",map[i]);
for(i = ; i<n; i++)
{
for(j = ; j<m; j++)
{
if(map[i][j]=='S')
{
sx = i;
sy = j;
}
}
}
memset(vis,,sizeof(vis));
bfs();
printf("%d\n",ans);
} return ;
}