#include <bits/stdc++.h>
using namespace std;
int main() {
  int z;
  for (cin >> z; z--;) {
    int r, c;
    cin >> r >> c;
    vector<string> grid(r);
    for (int i = 0; i < r; i++) cin >> grid[i];
    vector<int> rows(r), cols(c);
    int total = 0;
    for (int i = 0; i < r; i++) {
      for (int j = 0; j < c; j++) {
        if (grid[i][j] == 'A') rows[i]++, cols[j]++, total++;
      }
    }
    if (total == r * c) {
      cout << 0 << endl;
      continue;
    }
    if (total == 0) {
      cout << "MORTAL" << endl;
      continue;
    }
    if (rows[0] == c || rows.back() == c || cols[0] == r || cols.back() == r) {
      cout << 1 << endl;
      continue;
    }
    if (grid[0][0] == 'A' || grid[0].back() == 'A' || grid.back()[0] == 'A' ||
        grid.back().back() == 'A') {
      cout << 2 << endl;
      continue;
    }
    if (*max_element(rows.begin(), rows.end()) == c ||
        *max_element(cols.begin(), cols.end()) == r) {
      cout << 2 << endl;
      continue;
    }
    if (rows[0] || rows.back() || cols[0] || cols.back()) {
      cout << 3 << endl;
      continue;
    }
    cout << 4 << endl;
  }
}
