#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 10;
const long long P = 998244353;
char a[100][100];
long long n, m;
int flag;
long long cnt_all, cnt_edge, cnt_corner;
int t0() {
  cnt_all = cnt_edge = cnt_corner = 0;
  flag = 0;
  for (long long i = 1; i <= n; ++i)
    for (long long j = 1; j <= m; ++j)
      if (a[i][j] == 'A') {
        ++cnt_all;
        long long c = (i == 1 || i == n) + (j == 1 || j == m);
        if (c == 1) ++cnt_edge;
        if (c == 2) ++cnt_corner;
      }
  return cnt_all == n * m;
}
int t1() {
  for (long long i = 1; i <= n; ++i) {
    long long tmp = 0;
    for (long long j = 1; j <= m; ++j)
      if (a[i][j] == 'A') ++tmp;
    if (tmp == m) {
      if (i == 1 || i == n) return 1;
      flag = 1;
    }
  }
  for (long long j = 1; j <= m; ++j) {
    long long tmp = 0;
    for (long long i = 1; i <= n; ++i)
      if (a[i][j] == 'A') ++tmp;
    if (tmp == n) {
      if (j == 1 || j == m) return 1;
      flag = 1;
    }
  }
  return 0;
}
int t2() {
  if (a[1][1] == 'A' || a[1][m] == 'A' || a[n][1] == 'A' || a[n][m] == 'A')
    return 1;
  else {
    return 0;
  }
}
int t3() {
  for (int i = 2; i <= n - 1; i++) {
    if (a[i][1] == 'A') return 1;
  }
  for (int i = 2; i <= n - 1; i++) {
    if (a[i][m] == 'A') return 1;
  }
  for (int i = 2; i <= m - 1; i++) {
    if (a[1][i] == 'A') return 1;
  }
  for (int i = 2; i <= m - 1; i++) {
    if (a[n][i] == 'A') return 1;
  }
  return 0;
}
int t4() {
  for (int i = 2; i <= n - 1; i++)
    for (int j = 2; j <= m - 1; j++) {
      if (a[i][j] == 'A') return 1;
    }
  return 0;
}
int main() {
  int t;
  scanf("%d", &t);
  for (int i = 0; i < t; i++) {
    memset(a, 0, sizeof(a));
    n = 0, m = 0;
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; i++) scanf("%s", a[i] + 1);
    if (t0()) {
      cout << 0 << endl;
      continue;
    }
    if (t1()) {
      cout << 1 << endl;
      continue;
    }
    if (cnt_corner || flag) {
      cout << 2 << endl;
      continue;
    } else if (cnt_edge) {
      cout << 3 << endl;
      continue;
    } else if (cnt_all) {
      cout << 4 << endl;
      continue;
    } else {
      cout << "MORTAL" << endl;
      continue;
    }
  }
  return 0;
}
