#include <bits/stdc++.h>
using namespace std;
void swap(long long &a, long long &b) {
  auto tm = a;
  a = b;
  b = tm;
}
const long long mod = 1000000007;
const long long mod2 = 998244353;
const long long INF = (1LL << 50) - 1;
const long long N = 2e5 + 25;
bool a[60][60];
long long n, m;
bool chk1() {
  bool f = 0;
  for (long long(i) = (0); (i) < (n); ++(i))
    for (long long(j) = (0); (j) < (m); ++(j))
      if (a[i][j]) f = 1;
  return f;
}
bool chk2() {
  bool f = 0;
  for (long long(i) = (0); (i) < (n); ++(i))
    if (a[i][0] || a[i][m - 1]) f = 1;
  for (long long(i) = (0); (i) < (m); ++(i))
    if (a[0][i] || a[n - 1][i]) f = 1;
  return f;
}
bool chk3() {
  bool f1 = 1, f2 = 1, f3 = 1, f4 = 1;
  for (long long(i) = (0); (i) < (n); ++(i)) {
    if (a[i][0] == 0) f1 = 0;
    if (a[i][m - 1] == 0) f2 = 0;
  }
  for (long long(i) = (0); (i) < (m); ++(i)) {
    if (a[0][i] == 0) f3 = 0;
    if (a[n - 1][i] == 0) f4 = 0;
  }
  if (f1 || f2 || f3 || f4) return 1;
  return 0;
}
bool chk4() {
  for (long long(i) = (0); (i) < (n); ++(i)) {
    long long f = 1;
    for (long long(j) = (0); (j) < (m); ++(j))
      if (a[i][j] == 0) f = 0;
    if (f) return 1;
  }
  for (long long(i) = (0); (i) < (m); ++(i)) {
    long long f = 1;
    for (long long(j) = (0); (j) < (n); ++(j))
      if (a[j][i] == 0) f = 0;
    if (f) return 1;
  }
  return 0;
}
void bheja_fry() {
  cin >> n >> m;
  char ch;
  bool f = 1;
  for (long long(i) = (0); (i) < (n); ++(i)) {
    for (long long(j) = (0); (j) < (m); ++(j)) {
      cin >> ch;
      if (ch == 'A')
        a[i][j] = 1;
      else
        a[i][j] = 0, f = 0;
    }
  }
  if (f) {
    cout << 0;
    return;
  }
  if (!chk1()) {
    cout << "MORTAL";
    return;
  }
  if (!chk2()) {
    cout << 4;
    return;
  }
  if (chk3()) {
    cout << 1;
    return;
  }
  if (chk4() || a[n - 1][m - 1] || a[0][0] || a[n - 1][0] || a[0][m - 1]) {
    cout << 2;
    return;
  }
  cout << 3;
}
signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long t = 1;
  cin >> t;
  for (long long(i) = (1); (i) < (t + 1); ++(i)) {
    bheja_fry();
    if (i < t) cout << "\n";
  }
  return 0;
}
