#include <bits/stdc++.h>
using namespace std;
const int N = 2e2 + 10;
long long mp[N];
long long rmp[N];
bool full(long long x, int n) {
  for (int i = 1; i <= n; i++) {
    if (!(x & (1ll << i))) return false;
  }
  return true;
}
int work(int n, int m) {
  if (mp[1] & (1ll << 1)) return 2;
  if (mp[1] & (1ll << m)) return 2;
  if (mp[n] & (1ll << 1)) return 2;
  if (mp[n] & (1ll << m)) return 2;
  for (int i = 1; i <= n; i++)
    if (full(mp[i], m)) return 2;
  for (int i = 1; i <= m; i++)
    if (full(rmp[i], n)) return 2;
  return 3;
}
int main() {
  ios::sync_with_stdio(false);
  string s;
  int t;
  cin >> t;
  while (t--) {
    memset(mp, 0, sizeof mp);
    memset(rmp, 0, sizeof rmp);
    int n, m;
    cin >> n >> m;
    bool allP = true, allA = true;
    for (int i = 1; i <= n; i++)
      for (int j = 1; j <= m; j++) {
        char ch;
        cin >> ch;
        if (ch == 'A') {
          allP = false;
          mp[i] |= 1ll << j;
          rmp[j] |= 1ll << i;
        } else
          allA = false;
      }
    if (allP) {
      cout << "MORTAL" << endl;
      continue;
    }
    if (allA) {
      cout << 0 << endl;
      continue;
    }
    if (!(mp[1] || mp[n] || rmp[1] || rmp[m])) {
      cout << 4 << endl;
      continue;
    }
    if (full(mp[1], m) || full(mp[n], m) || full(rmp[1], n) ||
        full(rmp[m], n)) {
      cout << 1 << endl;
      continue;
    }
    cout << work(n, m) << endl;
  }
}
