#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
#define maxn 5500
#define inf 0x3f3f3f3f
int t,m,n,sx,sy,sum,ans;
char mmp[maxn][maxn];
int g[maxn][maxn];
bool vis[maxn][maxn];
int to[5][4]= {{1,0},{0,1},{-1,0},{0,-1}};
bool judge1(int x,int y)
{
if(x>=0&&x<n&&y>=0&&y<m)
{
if(mmp[x][y]!='#'&&vis[x][y]==0)
return true;
}
return false;
}
bool judge2(int x,int y)
{
if(x>=0&&x<n&&y>=0&&y<m)
{
if(mmp[x][y]=='.'&&vis[x][y]==0)
return true;
}
return false;
}
bool judge3(int x,int y)
{
if(x==0||y==0||x==n-1||y==m-1)
return true;
return false;
}
struct node
{
int x,y,cnt;
} top,temp;
queue<node>q;
void bfs()
{
while(!q.empty())
{
top=q.front();
q.pop();
g[top.x][top.y]=top.cnt;
for(int i=0; i<4; i++)
{
temp.x=top.x+to[i][0];
temp.y=top.y+to[i][1];
temp.cnt=top.cnt+1;
if(judge1(temp.x,temp.y))
{
vis[temp.x][temp.y]=1;
q.push(temp);
}
}
}
}
int bfs2()
{
queue<node>Q;
Q.push((node)
{
sx,sy,0
});
vis[sx][sy]=1;
while(!Q.empty())
{
top=Q.front();
Q.pop();
if(judge3(top.x,top.y))
{
if(g[top.x][top.y]>top.cnt)
{
return top.cnt;
}
}
for(int i=0; i<4; i++)
{
temp.x=top.x+to[i][0];
temp.y=top.y+to[i][1];
temp.cnt=top.cnt+1;
if(judge2(temp.x,temp.y))
{
if(g[temp.x][temp.y]>temp.cnt)
{
vis[temp.x][temp.y]=1;
Q.push(temp);
}
}
}
}
return -1;
}
int main()
{
ios::sync_with_stdio(false);
cin>>t;
while(t--)
{
memset(vis,0,sizeof(vis));
while(!q.empty())
q.pop();
sum=0;
cin>>n>>m;
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
g[i][j]=inf;
cin>>mmp[i][j];
if(mmp[i][j]=='J')
{
sx=i;
sy=j;
}
else if(mmp[i][j]=='F')
{
sum++;
q.push((node)
{
i,j,0
});
vis[i][j]=1;
}
}
}
bfs();
memset(vis,0,sizeof(vis));
ans=bfs2();
if(ans==-1)
cout<<"IMPOSSIBLE"<<endl;
else
cout<<ans+1<<endl;
}
return 0;
}