#include<stdio.h> #include<string.h> #include<stdlib.h> const int maxn=1010; struct node{ int x,y,s; }; char str[maxn]; bool p[maxn][maxn],a[maxn][maxn]; int t[maxn][maxn],d[4][2]={{1,0},{0,1},{-1,0},{0,-1}}; struct node q[maxn*maxn]; void din(int i,int x1,int y1,int s1){ q[i].x=x1;q[i].y=y1;q[i].s=s1; } int main(){ #ifndef ONLINE_JUDGE freopen("uva11624.in","r",stdin); freopen("uva11624.out","w",stdout); #endif int i,j,k,k1,m,n; int xs,ys,e,T; int f,l,u,v,w; scanf("%d",&T); while(T--){ memset(p,0,sizeof(p)); memset(a,0,sizeof(a)); scanf("%d%d",&n,&m); for(i=1;i<=n;i++) for(j=1;j<=m;j++) t[i][j]=999999; f=0;l=0; getchar(); for(i=1;i<=n;i++){ gets(str); for(j=0;j<m;j++){ if(str[j]!='#') a[i][j+1]=1; if(str[j]=='J'){ xs=i;ys=j+1; } if(str[j]=='F'){ din(++l,i,j+1,0); p[i][j+1]=1; t[i][j+1]=0; } } } if(xs==1 || xs==n || ys==1 || ys==m){ printf("1\n"); continue; } while(f<l){ f++; u=q[f].x;v=q[f].y;w=q[f].s; for(i=0;i<=3;i++) if(!p[u+d[i][0]][v+d[i][1]] && a[u+d[i][0]][v+d[i][1]]){ p[u+d[i][0]][v+d[i][1]]=1; din(++l,u+d[i][0],v+d[i][1],w+1); t[u+d[i][0]][v+d[i][1]]=w+1; } } memset(p,0,sizeof(p)); int flag=0,ans; f=0;l=1; din(1,xs,ys,0); while(f<l){ ++f; u=q[f].x;v=q[f].y;w=q[f].s; for(i=0;i<=3;i++) if(!p[u+d[i][0]][v+d[i][1]] && a[u+d[i][0]][v+d[i][1]] && (w+1)<t[u+d[i][0]][v+d[i][1]]){ p[u+d[i][0]][v+d[i][1]]=1; din(++l,u+d[i][0],v+d[i][1],w+1); if(q[l].x==1 || q[l].x==n || q[l].y==1 || q[l].y==m){ ans=q[l].s+1;flag=1;break; } } if(flag)break; } if(flag) printf("%d\n",ans); else puts("IMPOSSIBLE"); } return 0; }