#include <bits/stdc++.h>
using namespace std;
int read() {
  int x = 0;
  bool flg = false;
  char ch = getchar();
  for (; !isdigit(ch); ch = getchar())
    if (ch == '-') flg = true;
  for (; isdigit(ch); ch = getchar()) x = (x << 3) + (x << 1) + (ch ^ 48);
  return flg ? -x : x;
}
int n, m;
char a[64][64];
void solve() {
  n = read(), m = read();
  for (int i(1), _i(n); i <= _i; i++) scanf("%s", a[i] + 1);
  int tot = 0;
  for (int i(1), _i(n); i <= _i; i++)
    for (int j(1), _j(m); j <= _j; j++) tot += a[i][j] == 'A';
  if (!tot) return puts("MORTAL"), void();
  if (tot == n * m) return puts("0"), void();
  {
    bool g = 1;
    for (int i(1), _i(n); i <= _i; i++) g = g && a[i][1] == 'A';
    if (g) return puts("1"), void();
    g = 1;
    for (int i(1), _i(n); i <= _i; i++) g = g && a[i][m] == 'A';
    if (g) return puts("1"), void();
    g = 1;
    for (int i(1), _i(m); i <= _i; i++) g = g && a[1][i] == 'A';
    if (g) return puts("1"), void();
    g = 1;
    for (int i(1), _i(m); i <= _i; i++) g = g && a[n][i] == 'A';
    if (g) return puts("1"), void();
  }
  {
    for (int x : {1, n})
      for (int y : {1, m})
        if (a[x][y] == 'A') return puts("2"), void();
    for (int i(1), _i(n); i <= _i; i++) {
      bool g = 1;
      for (int j(1), _j(m); j <= _j; j++) g = g && a[i][j] == 'A';
      if (g) return puts("2"), void();
    }
    for (int j(1), _j(m); j <= _j; j++) {
      bool g = 1;
      for (int i(1), _i(n); i <= _i; i++) g = g && a[i][j] == 'A';
      if (g) return puts("2"), void();
    }
  }
  {
    for (int i(1), _i(n); i <= _i; i++)
      for (int j(1), _j(m); j <= _j; j++) {
        if (a[i][j] == 'A' && (i == 1 || i == n || j == 1 || j == m))
          return puts("3"), void();
      }
  }
  puts("4");
}
int main() {
  for (int T = read(); T--;) solve();
  return 0;
}
