#include <bits/stdc++.h>
const int maxn = 1000050;
using namespace std;
int n, m;
char x[100][100];
int r[100], c[100];
int main() {
  int T;
  cin >> T;
  while (T--) {
    scanf("%d%d", &n, &m);
    getchar();
    int i, j;
    int ans = 5;
    bool flag = 1;
    for (j = 1; j <= m; j++) c[j] = 0;
    for (i = 1; i <= n; i++) {
      r[i] = 0;
      for (j = 1; j <= m; j++) {
        x[i][j] = getchar();
        if (x[i][j] == 'A') {
          r[i]++;
          c[j]++;
          ans = min(ans, 4);
          if (i == 1 || i == n) {
            ans = min(ans, 3);
            if (j == 1 || j == m) ans = min(ans, 2);
          }
          if (j == 1 || j == m) {
            ans = min(ans, 3);
            if (i == 1 || i == n) ans = min(ans, 2);
          }
        } else
          flag = 0;
      }
      getchar();
    }
    if (ans == 5) {
      puts("MORTAL");
      continue;
    }
    if (flag) {
      puts("0");
      continue;
    }
    for (i = 1; i <= n; i++) {
      if (r[i] == m) {
        ans = min(ans, 2);
        if (i == 1 || i == n) ans = min(ans, 1);
      }
    }
    for (j = 1; j <= m; j++) {
      if (c[j] == n) {
        ans = min(ans, 2);
        if (j == 1 || j == m) ans = min(ans, 1);
      }
    }
    printf("%d\n", ans);
  }
}
