#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1e9 + 7;
const long long LLINF = 1e18 + 7;
int tab[100][100];
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  ;
  int t, r, c;
  cin >> t;
  while (t--) {
    int ans = 100;
    cin >> r >> c;
    string s;
    bool ok = false;
    bool zero = true;
    bool onborder = false;
    for (int i = 0; i < r; i++) {
      cin >> s;
      for (int j = 0; j < c; j++) {
        tab[i][j] = s[j] == 'A';
        if (tab[i][j]) ok = true;
        if (!tab[i][j]) zero = false;
        if (tab[i][j] && (i == 0 || i == r - 1 || j == 0 || j == c - 1))
          onborder = true;
      }
    }
    if (!ok) {
      cout << "MORTAL\n";
      continue;
    }
    if (zero) {
      cout << 0 << '\n';
      continue;
    }
    if (!onborder) {
      cout << 4 << '\n';
      continue;
    }
    ans = 3;
    for (int i = 0; i < r; i++) {
      bool whole = true;
      for (int j = 0; j < c; j++) {
        if (!tab[i][j]) {
          whole = false;
        }
      }
      if (whole) {
        if (i == 0 || i == r - 1) {
          ans = 1;
        }
        ans = min(ans, 2);
      }
    }
    for (int j = 0; j < c; j++) {
      bool whole = true;
      for (int i = 0; i < r; i++) {
        if (!tab[i][j]) {
          whole = false;
        }
      }
      if (whole) {
        if (j == 0 || j == c - 1) {
          ans = 1;
        }
        ans = min(ans, 2);
      }
    }
    if (tab[0][0] || tab[r - 1][0] || tab[0][c - 1] || tab[r - 1][c - 1]) {
      ans = min(ans, 2);
    }
    cout << ans << '\n';
  }
}
