#include```
#include<stdio.h>
#include
#include<string.h>
using namespace std;
char map[1011][1011];
int book_p[1011][1011];
int book_f[1011][1011];
int mi[1011][1011];
int n,m;
struct person{
int x;
int y;
int minute;
};
struct fire{
int x;
int y;
int minute;
};
int next1[4][2]={
{1,0},{0,1},{-1,0},{0,-1}
};
int sx,sy;
void bfs_f()
{
struct fire temp;
queue f;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
mi[i][j]=1000000000;
if(map[i][j]=='F')
{
temp.x=i;
temp.y=j;
temp.minute=0;
f.push(temp);
book_f[i][j]=1;
mi[i][j]=0;
}
}
}
struct fire a;
while(!f.empty())
{
temp=f.front();
f.pop();
for(int i=0;i<4;i++)
{
a=temp;
a.x+=next1[i][0];
a.y+=next1[i][1];
a.minute+=1;
if(a.x<0||a.y<0||a.x>=n||a.y>=m||book_f[a.x][a.y]||map[a.x][a.y]=='#'||map[a.x][a.y]=='F')
continue;
f.push(a);
book_f[a.x][a.y]=1;
mi[a.x][a.y]=a.minute;
}
}
}
int bfs_p()
{
int ans=0,flag=0;
if(map[sx][sy]==‘F’) return -1;
struct person t1,t2,t3;
queue p;
t1.x=sx;
t1.y=sy;
t1.minute=0;
p.push(t1);
book_p[sx][sy]=1;
while(!p.empty())
{
t2=p.front();
p.pop();
for(int i=0;i<4;i++)
{
t3=t2;
t3.x+=next1[i][0];
t3.y+=next1[i][1];
t3.minute+=1;
if(t3.x<0||t3.y<0||t3.x>=n||t3.y>=m){
flag=1;
ans=t3.minute;
break;
}
if(map[t3.x][t3.y]=='#'||book_p[t3.x][t3.y]||map[t3.x][t3.y]=='F'||t3.minute>=mi[t3.x][t3.y])
continue;
p.push(t3);
book_p[t3.x][t3.y]=1;
}
if(flag) break;
}
if(flag) return ans;
else return -1;
}
int main(void)
{
int ans;
int T;
scanf("%d",&T);
while(T–)
{
memset(book_f,0,sizeof(book_f));
memset(book_p,0,sizeof(book_p));
memset(mi,0,sizeof(mi));
ans=0;
scanf("%d%d",&n,&m);
getchar();
for(int i=0;i<n;i++)
{
scanf("%s",map[i]);
for(int j=0;map[i][j];j++)
{
if(map[i][j]==‘J’)
{
sx=i;
sy=j;
}
}
}
bfs_f();
ans=bfs_p();
if(ans!=-1) printf("%d\n",ans);
else printf(“IMPOSSIBLE\n”);
}
return 0;
}