import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main
{
public static char[][] arr;
public static int[][] fire;
public static int[][] move =
{
{ 0, 1 },
{ 1, 0 },
{ -1, 0 },
{ 0, -1 } };
public static void main(String args[])
{
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader sc = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
int p = sc.nextInt();
while (p-- > 0)
{
int a = sc.nextInt();
int b = sc.nextInt();
arr = new char[a][b];
fire = new int[a][b];
boolean pd[][] = new boolean[a][b];
Queue<change> joe = new LinkedList<change>();
for (int i = 0; i < fire.length; i++)
{
for (int j = 0; j < fire[i].length; j++)
{
fire[i][j] = Integer.MAX_VALUE;
}
}
Queue<change> x = new LinkedList<change>();
for (int i = 0; i < arr.length; i++)
{
arr[i] = sc.next().toCharArray();
for (int j = 0; j < b; j++)
{
if (arr[i][j] == 'F')
{
x.add(new change(i, j, 1));
}
if (arr[i][j] == 'J')
{
joe.add(new change(i, j, 1));
}
}
}
while (!x.isEmpty())
{
change ok = x.poll();
fire[ok.x][ok.y] = ok.step;
for (int i = 0; i < move.length; i++)
{
int o = ok.x + move[i][0];
int k = ok.y + move[i][1];
if (o >= 0 && o < a && k >= 0 && k < b && arr[o][k] != '#' && ok.step + 1 < fire[o][k])
{
x.add(new change(o, k, ok.step + 1));
fire[o][k] = ok.step + 1;
}
}
}
boolean gg = false;
while (!joe.isEmpty())
{
change ok = joe.poll();
if (ok.step >= fire[ok.x][ok.y])
{
continue;
}
if (ok.x == 0 || ok.x == a - 1 || ok.y == 0 || ok.y == b - 1)
{
gg = true;
System.out.println(ok.step);
break;
}
for (int i = 0; i < 4; i++)
{
int o = ok.x + move[i][0];
int k = ok.y + move[i][1];
if (o >= 0 && o < a && k >= 0 && k < b && arr[o][k] != '#' && ok.step + 1 < fire[o][k]
&& pd[o][k] == false)
{
pd[o][k] = true;
joe.add(new change(o, k, ok.step + 1));
}
}
}
if (gg == false)
{
System.out.println("IMPOSSIBLE");
}
}
out.close();
}
static class InputReader
{
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream)
{
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next()
{
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
try
{
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e)
{
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
}
}
class change
{
int x, y, step;
public change(int x, int y, int step)
{
this.x = x;
this.y = y;
this.step = step;
}
}