https://www.jisuanke.com/course/1027/51106
#include<bits/stdc++.h>
using namespace std;
int n,m;
struct point{
int x,y,s;
int f=0;
};
int sx,sy,tx,ty;
queue<point> q;
char a[2001][2001];
int nxt[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
bool check[2001][2001][2]={false};
int main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
getchar();
for(int j=1;j<=m;j++)
{
scanf("%c",&a[i][j]);
if(a[i][j]=='S')
sx=i,sy=j;
else if(a[i][j]=='T')
tx=i,ty=j;
}
}
point t;
t.x=sx,t.y=sy,t.s=0;
q.push(t);//起点入队
check[sx][sy][t.f]=true;
while(!q.empty())
{
point u=q.front();q.pop();
for(int k=0;k<4;k++)
{
int nx=u.x+nxt[k][0],ny=u.y+nxt[k][1];
point te;
te.x=nx,te.y=ny,te.s=u.s+1,te.f=u.f;
if(nx<1||nx>n||ny<1||ny>m) continue;//越界判断
if(a[nx][ny]!='#'&&check[nx][ny][te.f]==false)
{
if(a[nx][ny]=='P'||te.f)
{ te.f=1;check[nx][ny][te.f]=true;}
else check[nx][ny][te.f]=true;
q.push(te);
}
if(nx==tx&&ny==ty&&check[tx][ty][1])
{
//check[tx][ty]=true;
//q.push(te);
break;
}
// printf("%d %d %d\n",te.x,te.y,te.s);
}
if(check[tx][ty][1]==true)
break;
}
if(check[tx][ty][1])
printf("%d",q.back().s);
return 0;
}