#include <bits/stdc++.h>
using namespace std;
const int MAX = 69;
const int MOD = 1000000007;
void solve() {
  int r, c;
  cin >> r >> c;
  char grid[MAX][MAX];
  int rows[r], cols[c], aCount = 0;
  for (int i = 0; i < r; i++) {
    rows[i] = 0;
  }
  for (int i = 0; i < c; i++) {
    cols[i] = 0;
  }
  char q;
  bool two = false;
  for (int i = 0; i < r; i++) {
    for (int j = 0; j < c; j++) {
      cin >> q;
      if (q == 'A') {
        rows[i]++;
        cols[j]++;
        aCount++;
      }
      if (((i == 0 || i == r - 1) && (j == 0 || j == c - 1)) && q == 'A') {
        two = true;
      }
      grid[i][j] = q;
    }
  }
  int rMax = -1, cMax = -1;
  for (int i = 0; i < r; i++) {
    rMax = max(rMax, rows[i]);
  }
  for (int i = 0; i < c; i++) {
    cMax = max(cMax, cols[i]);
  }
  if (aCount == 0) {
    cout << "MORTAL";
  } else if (aCount == r * c) {
    cout << 0;
  } else if (rows[0] == c || cols[0] == r || rows[r - 1] == c ||
             cols[c - 1] == r) {
    cout << 1;
  } else if (two || rMax == c || cMax == r) {
    cout << 2;
  } else if (rows[0] || cols[0] || rows[r - 1] || cols[c - 1]) {
    cout << 3;
  } else {
    cout << 4;
  }
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  int tt;
  cin >> tt;
  for (int i = 1; i <= tt; i++) {
    solve();
    cout << endl;
  }
}
