#include <bits/stdc++.h>
using namespace std;
long long r, c;
bool cx(long long x) {
  if (x == 0 || x == r - 1) return true;
  return false;
}
bool cy(long long y) {
  if (y == 0 || y == c - 1) return true;
  return false;
}
void solve() {
  cin >> r >> c;
  vector<vector<long long> > mat(r, vector<long long>(c));
  vector<long long> row(r), col(c);
  long long corner = 0, edge = 0, good = 0, one = 0;
  for (long long i = 0; i < r; i++) {
    for (long long j = 0; j < c; j++) {
      char a;
      cin >> a;
      (a == 'A') ? (mat[i][j] = 1) : (mat[i][j] = 0);
      row[i] += mat[i][j];
      col[j] += mat[i][j];
      if (row[i] == c) {
        corner = 1;
        if (cx(i)) one = 1;
      }
      if (col[j] == r) {
        corner = 1;
        if (cy(j)) one = 1;
      }
      if (mat[i][j]) {
        if (cx(i) || cy(j)) {
          edge = 1;
          if (cx(i) && cy(j)) {
            corner = 1;
          }
        }
      }
      good += mat[i][j];
    }
  }
  if (good == 0)
    cout << "MORTAL";
  else if (good == r * c)
    cout << 0;
  else if (one)
    cout << 1;
  else if (corner)
    cout << 2;
  else if (edge)
    cout << 3;
  else {
    cout << 4;
  }
  cout << '\n';
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long t, tt;
  cin >> t;
  tt = t;
  while (tt--) {
    solve();
  }
}
