广搜板子,加个方向就好了 注意多测清空问题
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
#define int long long
const int N = 1e5+10;
const int inf = 0x3f3f3f3f;
const int mod = 1e9+7;
int n,m;
char g[1010][1010];
bool vis[1010][1010][5];
struct Node{
int x,y,f;
};
int stx,sty,edx,edy;
int dx[] = {0,0,1,-1};int dy[] = {1,-1,0,0};
int dist[1010][1010];
void bfs()
{
queue<Node>q;
for(int i=0;i<4;i++)q.push({stx,sty,i});
memset(dist,0x3f,sizeof dist);
memset(vis,0,sizeof vis);
dist[stx][sty] = 0;
vis[stx][sty][0] = 1;
vis[stx][sty][1] = 1;
vis[stx][sty][2] = 1;
vis[stx][sty][3] = 1;
while(q.size())
{
auto t = q.front();
int x = t.x,y = t.y,f = t.f;
q.pop();
int temx = x+dx[f],temy = y+dy[f];
if(temx<1||temy<1||temx>n||temy>m)continue;
if(g[temx][temy]=='#'||vis[temx][temy][f])continue;
vis[temx][temy][f] = true;
dist[temx][temy] = dist[x][y]+1;
if(g[temx][temy]=='.')q.push({temx,temy,f});
else if(g[temx][temy]=='*'){
q.push({temx,temy,0});
q.push({temx,temy,1});
q.push({temx,temy,2});
q.push({temx,temy,3});
}else if(g[temx][temy]=='T'){
cout<<dist[temx][temy]<<"\n";return;
}
}
cout<<-1<<"\n";
}
void solve()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++){
cin>>g[i][j];
if(g[i][j]=='S'){stx = i,sty = j;}
}
bfs();
}
signed main()
{
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int _;
cin>>_;
//_ = 1;
while(_--)solve();
return 0;
}