#include <bits/stdc++.h>
using namespace std;
using namespace std::chrono;
const int long long mod = 1000000007ll;
const int long long smod = 998244353ll;
const int long long inf = 10000000000000007ll;
const double eps = 1e-10;
const int long long MAXN = 1000006;
int long long T;
string a[MAXN];
int long long r, c;
bool check_row(int long long i) {
  bool f = true;
  for (int long long j = 0; j < c; j++) {
    if (a[i][j] != 'A') {
      f = false;
    }
  }
  return f;
}
bool check_col(int long long j) {
  bool f = true;
  for (int long long i = 0; i < r; i++) {
    if (a[i][j] != 'A') {
      f = false;
    }
  }
  return f;
}
bool check_in_row(int long long i) {
  bool f = false;
  for (int long long j = 0; j < c; j++) {
    if (a[i][j] == 'A') {
      f = true;
    }
  }
  return f;
}
bool check_in_col(int long long j) {
  bool f = false;
  for (int long long i = 0; i < r; i++) {
    if (a[i][j] == 'A') {
      f = true;
    }
  }
  return f;
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cout.precision(15);
  cout.setf(ios::fixed);
  cin >> T;
  for (int long long tt = 1; tt <= T; tt++) {
    cin >> r >> c;
    for (int long long i = 0; i < r; i++) {
      cin >> a[i];
    }
    int long long ac = 0;
    for (int long long i = 0; i < r; i++) {
      for (int long long j = 0; j < c; j++) {
        ac += a[i][j] == 'A' ? 1 : 0;
      }
    }
    if (ac == r * c) {
      cout << 0 << endl;
      continue;
    }
    if (ac == 0) {
      cout << "MORTAL" << endl;
      continue;
    }
    bool f1 =
        check_row(0) || check_row(r - 1) || check_col(0) || check_col(c - 1);
    if (f1) {
      cout << 1 << endl;
      continue;
    }
    bool f2 = a[0][0] == 'A' || a[r - 1][0] == 'A' || a[0][c - 1] == 'A' ||
              a[r - 1][c - 1] == 'A';
    for (int long long i = 0; i < r; i++) {
      f2 |= check_row(i);
    }
    for (int long long j = 0; j < c; j++) {
      f2 |= check_col(j);
    }
    if (f2) {
      cout << 2 << endl;
      continue;
    }
    bool f3 = check_in_row(0) || check_in_row(r - 1) || check_in_col(0) ||
              check_in_col(c - 1);
    if (f3) {
      cout << 3 << endl;
      continue;
    }
    cout << 4 << endl;
  }
  return 0;
}
