#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  cin >> t;
  while (t--) {
    int r, c;
    cin >> r >> c;
    string str[r];
    for (int i = 0; i < r; i++) cin >> str[i];
    int total = 0;
    vector<int> row(r), col(c);
    for (int i = 0; i < r; i++) {
      for (int j = 0; j < c; j++) {
        if (str[i][j] == 'A') {
          total++;
          row[i]++;
          col[j]++;
        }
      }
    }
    if (total == 0)
      cout << "MORTAL\n";
    else if (total == r * c)
      cout << "0\n";
    else if (row[0] == c | col[0] == r || row[r - 1] == c || col[c - 1] == r)
      cout << "1\n";
    else if ((*max_element(row.begin(), row.end()) == c) ||
             (*max_element(col.begin(), col.end()) == r) || str[0][0] == 'A' ||
             str[0][c - 1] == 'A' || str[r - 1][0] == 'A' ||
             str[r - 1][c - 1] == 'A')
      cout << "2\n";
    else if (row[0] || row[r - 1] || col[0] || col[c - 1])
      cout << "3\n";
    else
      cout << "4\n";
  }
  return 0;
}
