#include <bits/stdc++.h>
using namespace std;
void solve() {
  int n, m;
  cin >> n >> m;
  vector<vector<int>> a(n, vector<int>(m));
  vector<int> f(n);
  vector<int> s(m);
  int cnt = 0;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      char c;
      cin >> c;
      a[i][j] = (c == 'A');
      cnt += a[i][j];
      s[j] += a[i][j];
      f[i] += a[i][j];
    }
  }
  if (cnt == 0) {
    cout << "MORTAL\n";
    return;
  }
  if (cnt == n * m) {
    cout << "0\n";
    return;
  }
  int ans = 4;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      if (a[i][j]) {
        int di = 2;
        if (i == 0 || i + 1 == n) {
          di--;
        }
        int dj = 2;
        if (j == 0 || j + 1 == m) {
          dj--;
        }
        if (f[i] == m || s[j] == n) {
          ans = min(ans, di + dj - 1);
        }
        ans = min(ans, di + dj);
      }
    }
  }
  cout << ans << '\n';
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  int q;
  cin >> q;
  while (q--) {
    solve();
  }
}
