#include <bits/stdc++.h>
using namespace std;
int t, n, m;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0), cout.tie(0);
  cin >> t;
  while (t--) {
    cin >> n >> m;
    vector<int> r(n, 0), c(m, 0);
    int rez = 4, nr = 0;
    bool ok = 0;
    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < m; ++j) {
        char a;
        cin >> a;
        if (a == 'A') {
          ok = 1;
          if (!i || i == n - 1 || !j || j == m - 1) rez = min(rez, 3);
          if ((!i && !j) || (!i && j == m - 1) || (i == n - 1 && !j) ||
              (i == n - 1 && j == m - 1))
            rez = min(rez, 2);
          ++r[i];
          ++c[j];
          ++nr;
        }
      }
    }
    if (nr == n * m) {
      cout << "0\n";
      continue;
    }
    for (int i = 0; i < n; ++i) {
      if (r[i] == m) rez = min(rez, 2);
    }
    for (int i = 0; i < m; ++i) {
      if (c[i] == n) rez = min(rez, 2);
    }
    if (!ok) {
      cout << "MORTAL\n";
      continue;
    }
    if (r[0] == m || r[n - 1] == m || c[0] == n || c[m - 1] == n) {
      cout << "1\n";
      continue;
    }
    cout << rez << '\n';
  }
  return 0;
}
