// Crazy King
import java.util.Scanner;
public class Solution {
static int[] X = new int[10000000];
static int[] Y = new int[10000000];
static int[] T = new int[10000000];
static int l, r;
static int[][] Ts;
static int[] Dx = {0, 0, -1, 1, -1, -1, 1, 1};
static int[] Dy = {-1, 1, 0, 0 ,-1, 1, -1, 1};
static int[] Mx = {-2, -2, -1, -1, 2, 2, 1, 1};
static int[] My = {-1, 1, -2, 2, -1, 1, -2, 2};
static char[][] A;
static boolean[][] Check;
public static void main(String[] args) {
//System.setIn(new FileInputStream("king.txt"));
Scanner sc = new Scanner(System.in);
int testCase = sc.nextInt();
for (int tc = 1; tc <= testCase; tc++) {
int col = sc.nextInt() + 4;
int row = sc.nextInt() + 4;
A = new char[row][col];
Ts = new int[row][col];
for (int i = 0; i < A.length; i++) {
A[i][0] = 'Z'; Ts[i][0] = -1;
A[i][1] = 'Z'; Ts[i][1] = -1;
A[i][A[0].length - 1] = 'Z'; Ts[i][A[0].length - 1] = -1;
A[i][A[0].length - 2] = 'Z'; Ts[i][A[0].length - 2] = -1;
}
for (int i = 0; i < A[0].length; i++) {
A[0][i] = 'Z';
A[1][i] = 'Z';
A[A.length - 1][i] = 'Z';
A[A.length - 2][i] = 'Z';
Ts[0][i] = -1;
Ts[1][i] = -1;
Ts[A.length - 1][i] = -1;
Ts[A.length - 2][i] = -1;
}
l = -1; r = -1;
Check = new boolean[row][col];
int vuaX = 0, vuaY = 0;
for (int i = 2; i < A.length - 2; i++) {
String s = sc.next();
for (int j = 2; j < A[0].length - 2; j++) {
A[i][j] = s.charAt(j - 2);
if(A[i][j] == 'Z') {
push(i, j, 1);
}
if(A[i][j] == 'A') {
vuaX = i;
vuaY = j;
Check[i][j] = true;
}
}
}
nguaLan();
int res = 0;
l = -1; r = -1;
pushVua(vuaX, vuaY, 1);
int k = 0;
while(l != r) {
int x = X[++l];
int y = Y[l];
int t = T[l];
for (int i = 0; i < 8; i++) {
int dx = x + Dx[i];
int dy = y + Dy[i];
if(A[dx][dy] == 'B') {
res = t + 1;
k = 1;
break;
}
if(A[dx][dy] == '.' && !Check[dx][dy]) {
Check[dx][dy] = true;
pushVua(dx, dy, t + 1);
}
}
if(res != 0) break;
}
if(k == 0) res = 0;
System.out.println(res - 1);
}
}
static void pushVua(int x, int y, int t) {
X[++r] = x;
Y[r] = y;
T[r] = t;
}
static void nguaLan() {
while(l != r) {
int x = X[++l];
int y = Y[l];
int t = T[l];
for (int i = 0; i < 8; i++) {
int mx = x + Mx[i];
int my = y + My[i];
if(A[mx][my] == '.' ) {
A[mx][my] = 'Z';
}
}
}
}
static void push(int x, int y, int t) {
X[++r] = x;
Y[r] = y;
T[r] = t;
}
}