RT。TLE 4 个点。
#include<bits/stdc++.h>
#define ll long long
#define do double
#define pb push_back
#define il inline
#define lowbit(x) (x&(-x))
#define sqr(x) (x*x)
using namespace std;
const int maxn=1005;
int n,m,a[maxn][maxn];
int sx,sy,ans=2e9;
bool vis[maxn][maxn];
const int dx[]={-1,0,1,0};
const int dy[]={0,1,0,-1};
struct node{
int x,y,z;
}k[1005];int cnt;
void add(int x,int y,int z){
k[++cnt]=(node){x,y,z};
}
void bfs1(int x,int y){
// printf("\nbfs now:\n");
queue<node>q;
q.push((node){x,y,0});
while(!q.empty()){
node tmp=q.front();q.pop();
int x=tmp.x;int y=tmp.y;int z=tmp.z;
vis[x][y]=1;
// printf("%d %d %d\n",x,y,z);
for(int i=0;i<4;++i){
int xx=x+dx[i];
int yy=y+dy[i];
if(vis[xx][yy]
||xx<1||yy<1||xx>n||yy>m
||a[xx][yy]==1||a[xx][yy]==3) continue;
if(a[xx][yy]==4) q.push((node){xx,yy,z+1}),add(xx,yy,z+1);
if(a[xx][yy]==0) q.push((node){xx,yy,z+1});
}
}
}
int bfs2(int x,int y){
// printf("\nbfs now:\n");
memset(vis,0,sizeof(vis));
queue<node>q;
q.push((node){x,y,0});
while(!q.empty()){
node tmp=q.front();q.pop();
int x=tmp.x;int y=tmp.y;int z=tmp.z;
vis[x][y]=1;
// printf("%d %d %d\n",x,y,z);
for(int i=0;i<4;++i){
int xx=x+dx[i];
int yy=y+dy[i];
if(vis[xx][yy]||xx<1||yy<1||xx>n||yy>m||a[xx][yy]==1) continue;
if(a[xx][yy]==3) return z+1;
if(a[xx][yy]==0||a[xx][yy]==4) q.push((node){xx,yy,z+1});
}
}
}
signed main(){
scanf("%d%d",&n,&m);
swap(n,m);
for(int i=1;i<=n;++i)
for(int j=1;j<=m;++j){
scanf("%d",&a[i][j]);
if(a[i][j]==2) sx=i,sy=j,a[i][j]=0;
}
bfs1(sx,sy);
for(int i=1;i<=cnt;++i)
ans=min(ans,bfs2(k[i].x,k[i].y)+k[i].z);
printf("%d",ans);
return 0;
}