#include <iostream>
#include<bits/stdc++.h>
#include<fstream>
#define inf 0x3f3f3f3f
using namespace std;
int r,c;
char board[1005][1005];
int b[1005][1005];
typedef pair<int,int> p;
p m,n;
bool book[1005][1005],book1[1005][1005];
int ax[4][2]={{-1,0},{0,1},{1,0},{0,-1}};
struct node
{
int x;
int y;
int step;
};
node now,temp;
queue<p>q1;
void init()
{
memset(book1,false,sizeof(book1));
//b[x][y]=0;
//q1.push(p(x,y));
//book1[x][y]=true;
while(q1.size())
{
p e=q1.front();
q1.pop();
int nx,ny;
for(int i=0;i<4;i++)
{
nx=e.first+ax[i][0];
ny=e.second+ax[i][1];
if(nx>=0&&nx<r&&ny>=0&&ny<c&&board[nx][ny]!='#'&&!book1[nx][ny])
{
q1.push(p(nx,ny));
book1[nx][ny]=true;
b[nx][ny]=b[e.first][e.second]+1;
}
}
}
// for(int i=0; i<r; i++)
// {
// for(int j=0; j<c; j++)
// printf("%d ",b[i][j]);
// printf("\n");
// }
}
void bfs()
{
memset(book,false,sizeof(book));
int flag=0;
now.x=m.first,now.y=m.second,now.step=0;
queue<node>q;
q.push(now);
book[now.x][now.y]=true;
while(q.size())
{
temp=q.front();
q.pop();
for(int i=0;i<4;i++)
{
now.x=temp.x+ax[i][0];
now.y=temp.y+ax[i][1];
now.step=temp.step+1;
if(now.x>=0&&now.x<r&&now.y>=0&&now.y<c&&!book[now.x][now.y]&&now.step<b[now.x][now.y]&&board[now.x][now.y]!='#')
{
q.push(now);
book[now.x][now.y]=true;
}
if(now.x<0||now.x>=r||now.y<0||now.y>=c)
{
flag=1;
printf("%d\n",now.step);
break;
}
}
if(flag)break;
}
if(!flag)printf("IMPOSSIBLE\n");
}
int main()
{
int t;
cin>>t;
while(t--)
{
memset(board,0,sizeof(board));
cin>>r>>c;
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
b[i][j]=inf;
}
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
cin>>board[i][j];
if(board[i][j]=='J')
m.first=i,m.second=j;
if(board[i][j]=='F')
{
b[i][j]=0;
book1[i][j]=true;
q1.push(p(i,j));
}
//init(i,j);
}
}
init();
bfs();
while(!q1.empty())
{
q1.pop();
}
}
return 0;
}