https://www.bnuoj.com/v3/problem_show.php?pid=49102
BFS
#include <bits/stdc++.h>
#define maxs 202020
#define mme(i,j) memset(i,j,sizeof(i))
using namespace std;
int way[5]= {1,0,-1,0};
int wax[5]= {0,1,0,-1};
char maps[102][102];
int n,m,sx,sy;
int ans;
bool vis[102][102][5];
struct node
{
int x,y;
int step;
int state;
} now,nex;
void bfs(int x,int y)// 2-3D
{
mme(vis,0);
now.x=x;
now.y=y;
now.state=2;
now.step=0;
vis[now.x][now.y][now.state]=1;
queue<node>q;
q.push(now);
node tp;
while(!q.empty())
{
now=q.front();
q.pop();
if(maps[now.x][now.y]=='1')
{
printf("%d\n",now.step);
return;
}
for(int i=0; i<4; i++)
{
nex.x=now.x+wax[i];
nex.y=now.y+way[i];
nex.step=now.step+1;
if(nex.x>0&&nex.x<=n&&nex.y>0&&nex.y<=m)
{
if(maps[nex.x][nex.y]=='.'||maps[nex.x][nex.y]=='0'||maps[nex.x][nex.y]=='1')
{
nex.state=now.state;
if(vis[nex.x][nex.y][nex.state]==0)
{
vis[nex.x][nex.y][nex.state]=1;
q.push(nex);
}
}
if(maps[nex.x][nex.y]=='#')continue;
if(maps[nex.x][nex.y]=='@')
{
nex.state=now.state;
if(vis[nex.x][nex.y][nex.state]==0)
{
vis[nex.x][nex.y][nex.state]=1;
q.push(nex);
}
nex.state=5-now.state;
if(vis[nex.x][nex.y][nex.state]==0)
{
vis[nex.x][nex.y][nex.state]=1;
q.push(nex);
}
}
if(maps[nex.x][nex.y] == '2') {
if(now.state==2) {
nex.state=now.state;
if(vis[ nex.x ][ nex.y ][ nex.state ] == 0) {
vis[ nex.x ][ nex.y ][ nex.state ] = 1;
q.push( nex );
}
}
else
continue;
}
if(maps[nex.x][nex.y]=='3'){
if(now.state==3){
nex.state=now.state;
if(vis[nex.x][nex.y][nex.state]==0){
vis[nex.x][nex.y][nex.state]=1;
q.push(nex);
}
}
else
continue;
}
}
}
}
printf("-1\n");
return;
}
void Solve()
{
ans=-1;
sx=sy=-1;
scanf("%d %d",&n,&m);
for(int i=1; i<=n; i++)scanf("%s",maps[i]+1);
for(int i=1; i<=n; i++)
{
for(int j=1; j<=m; j++)
{
if(maps[i][j]=='0')
{
sx=i;
sy=j;
break;
}
}
if(sx!=-1)
break;
}
if(sx==-1)
{
puts("-1");
return;
}
bfs(sx,sy);
return;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
Solve();
}
return 0;
}