#include"cstdio"
#include"queue"
#include"cstring"
using namespace std;
const int MAXN=;
const int INF=0X7fffffff;
typedef pair<int,int> P;
char mp[MAXN][MAXN];
int ft[MAXN][MAXN];
int jt[MAXN][MAXN];
int dx[]={,,-,};
int dy[]={,,,-};
int n,m;
int sy,sx;
void bfs1()//第一次广搜确定 fire到达passable square的时间
{
queue<P> que;
for(int i=;i<n;i++)
for(int j=;j<m;j++)
{
ft[i][j]=INF;
if(mp[i][j]=='F')
{
que.push(P(i,j));
ft[i][j]=;
}
}
while(!que.empty())
{
P now = que.front();que.pop();
for(int i=;i<;i++)
{
int ny=now.first+dy[i];
int nx=now.second+dx[i];
if(<=ny&&ny<n&&<=nx&&nx<m&&mp[ny][nx]!='#')
{
int dist=ft[now.first][now.second]+;
if(dist<ft[ny][nx])
{
ft[ny][nx]=dist;
que.push(P(ny,nx));
}
}
}
}
}
void bfs2()
{
memset(jt,-,sizeof(jt));
queue<P> que;
que.push(P(sy,sx));
jt[sy][sx]=;
while(!que.empty())
{
P now=que.front();que.pop();
if(now.first==||now.first==n-||now.second==||now.second==m-)
{
printf("%d\n",jt[now.first][now.second]+);//逃出迷宫,注意+1
return ;
}
for(int i=;i<;i++)
{
int ny=now.first+dy[i];
int nx=now.second+dx[i];
if(<=ny&&ny<n&&<=nx&&nx<m&&mp[ny][nx]!='#'&&jt[ny][nx]==-)
{
int dist=jt[now.first][now.second]+;
if(dist<ft[ny][nx])//若在该时刻该点没有火焰到达说明可行
{
jt[ny][nx]=dist;
que.push(P(ny,nx));
}
}
}
} printf("IMPOSSIBLE\n");
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
scanf("%*c");
for(int i=;i<n;i++)
{
for(int j=;j<m;j++)
{
scanf("%c",&mp[i][j]);
if(mp[i][j]=='J')
{
sy=i,sx=j;
}
}
scanf("%*c");
}
bfs1();
bfs2();
} return ;
}
05-12 07:05