#include <bits/stdc++.h>
using namespace std;
int main() {
  int q;
  cin >> q;
  while (q--) {
    int n, m;
    cin >> n >> m;
    bool allA = 1, allP = 1;
    vector<vector<int> > v(n, vector<int>(m));
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        char c;
        cin >> c;
        if (c == 'A') {
          allP = 0;
          v[i][j] = 1;
        } else
          allA = 0;
      }
    }
    if (allA) {
      cout << 0 << '\n';
      continue;
    }
    if (allP) {
      cout << "MORTAL\n";
      continue;
    }
    int ans = 4;
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        if (v[i][j]) {
          int now = 4;
          if (i == 0 || i == n - 1) now--;
          if (j == 0 || j == m - 1) now--;
          ans = min(ans, now);
        }
      }
    }
    for (int i = 0; i < n; i++) {
      if (find(v[i].begin(), v[i].end(), 0) == v[i].end())
        if (i == 0 || i == n - 1)
          ans = 1;
        else
          ans = min(ans, 2);
    }
    for (int j = 0; j < m; j++) {
      int ok = 1;
      for (int i = 0; i < n; i++) {
        ok &= v[i][j];
      }
      if (ok)
        if (j == 0 || j == m - 1)
          ans = 1;
        else
          ans = min(ans, 2);
    }
    cout << ans << '\n';
  }
}
