\(bfs\)裸题,加两个\(bool\)变量判断下一步是否能继续走就好了
const int N=1010;
char g[N][N];
int dist[N][N];
struct Node
{
int x,y;
bool F,M;
};
PII ed;
int n,m;
inline bool check(int x,int y)
{
return x>0 && x<=n && y>0 && y<=m;
}
int bfs(int x,int y)
{
memset(dist,-1,sizeof dist);
queue<Node> q;
q.push({x,y,0,0});
dist[x][y]=0;
while(q.size())
{
Node t=q.front();
int x=t.x,y=t.y;
q.pop();
if(x == ed.fi && y == ed.se) return dist[x][y];
for(int i=0;i<4;i++)
{
int a=x+dx[i],b=y+dy[i];
if(!check(a,b) || g[a][b] == '*') continue;
Node nt={a,b,0,0};
if(t.F) nt.F=true;
if(t.M) nt.M=true;
if(dist[a][b] == -1)
{
if(g[a][b] == 'F')
{
if(nt.M) continue;
else nt.F=true;
}
if(g[a][b] == 'M')
{
if(nt.F) continue;
else nt.M=true;
}
dist[a][b]=dist[x][y]+1;
q.push(nt);
}
}
}
return -1;
}
int main()
{
int T;
cin>>T;
while(T--)
{
cin>>n>>m>>ed.fi>>ed.se;
for(int i=1;i<=n;i++) scanf("%s",g[i]+1);
int t=bfs(1,1);
if(~t) cout<<t*2<<endl;
else puts("IMPOSSIBLE");
}
//system("pause");
}