BFS,开始没看题结果样例都过不去,后来看了题发现是要考虑转向的步数,加一个判断就可以了。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <vector>
#include <algorithm>
#include <queue>
#include <set>
using namespace std;
int dirx[]={0,0,1,-1};
int diry[]={1,-1,0,0};
int n,m,sx,sy,ex,ey;
bool vis[105][105][5];
char mp[105][105];
struct point
{
int x,y,step,dir;
friend bool operator < (const point& a,const point& b)
{
return a.step>b.step;
}
};
bool judge(int x,int y,int i)
{
return (x>=0&&x<n&&y>=0&&y<m&&!vis[x][y][i]&&mp[x][y]!='#');
}
int fuck(int x,int y)
{
if(x==0)
{
if(y==0)return 0;
if(y==1)return 2;
if(y==2)return 1;
if(y==3)return 1;
}if(x==1)
{
if(y==0)return 2;
if(y==1)return 0;
if(y==2)return 1;
if(y==3)return 1;
}if(x==2)
{
if(y==0)return 1;
if(y==1)return 1;
if(y==2)return 0;
if(y==3)return 2;
}if(x==3)
{
if(y==0)return 1;
if(y==1)return 1;
if(y==2)return 2;
if(y==3)return 0;
}
}
int bfs()
{
priority_queue <point> q;
point F,N;
F.x=sx;F.y=sy;
F.step=0;F.dir=3;
q.push(F);
vis[sx][sy][3]=true;
while(!q.empty())
{
F=q.top();q.pop();
if(F.x==ex&&F.y==ey)return F.step;
for(int i=0;i<4;++i)
{
N.x=F.x+dirx[i];
N.y=F.y+diry[i];
if(judge(N.x,N.y,i))
{
N.step=F.step+fuck(F.dir,i)+1;
N.dir=i;
q.push(N);
vis[N.x][N.y][i]=true;
}
}
}
return -1;
}
int main()
{
//freopen("in.txt", "r", stdin);
int T;scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
for(int i=0;i<n;++i)
{
scanf("%s",&mp[i]);
for(int j=0;j<m;++j)
{
if(mp[i][j]=='S')
{
sx=i;sy=j;
}
else if(mp[i][j]=='T')
{
ex=i;ey=j;
}
}
}
memset(vis,false,sizeof(vis));
printf("%d\n",bfs());
}
return 0;
}