#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> ii;
int R,C;
bool check(int x,int y){
return (x==0||y==0||x>R||y>C);
}
int main(){
int t;
cin>>t;
while(t--){
cin>>R>>C;
pair<int,int> fire,joey;
bool b[R+1][C+1];
memset(b,0,sizeof b);
queue<pair<pair<int,int>,int> > q;
for(int i=0;i<R;i++)
for(int j=0;j<C;j++){
char c;
cin>>c;
if(c=='#') b[i+1][j+1]=1;
else if(c=='.') b[i+1][j+1]=0;
else if(c=='J') joey=make_pair(i+1,j+1),b[i+1][j+1]=1;
else q.push(make_pair(ii(i+1,j+1),1e9)),b[i+1][j+1]=2;
}
q.push(make_pair(joey,0));
int dist=1e9;
while(!q.empty()){
auto Q=q.front();
q.pop();
pair<int,int> c=Q.first;
int x=c.first,y=c.second,z=Q.second;
if(check(x,y)) {dist=min(min(z,1000000000),dist);continue;}
if(check(x+1,y)||!b[x+1][y]) {q.push(make_pair(ii(x+1,y),z+1));if(!check(x+1,y)) b[x+1][y]=1;}
if(check(x-1,y)||!b[x-1][y]) {q.push(make_pair(ii(x-1,y),z+1));if(!check(x-1,y)) b[x-1][y]=1;}
if(check(x,y+1)||!b[x][y+1]) {q.push(make_pair(ii(x,y+1),z+1));if(!check(x,y+1)) b[x][y+1]=1;}
if(check(x,y-1)||!b[x][y-1]) {q.push(make_pair(ii(x,y-1),z+1));if(!check(x+1,y)) b[x][y-1]=1;}
}
if(dist==1000000000) cout<<"IMPOSSIBLE"<<endl;
else cout<<dist<<endl;
}
}
I2luY2x1ZGU8Yml0cy9zdGRjKysuaD4KdXNpbmcgbmFtZXNwYWNlIHN0ZDsKdHlwZWRlZiBwYWlyPGludCxpbnQ+IGlpOwppbnQgUixDOwogYm9vbCBjaGVjayhpbnQgeCxpbnQgeSl7CnJldHVybiAoeD09MHx8eT09MHx8eD5SfHx5PkMpOwoKCn0KaW50IG1haW4oKXsKCWludCB0OwoJY2luPj50OwoJd2hpbGUodC0tKXsKY2luPj5SPj5DOwpwYWlyPG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