#include <bits/stdc++.h>
using namespace std;
const int N = 100;
signed main() {
  int t;
  cin >> t;
  while (t--) {
    int r, c, cnt = 0, x = 0;
    cin >> r >> c;
    char a[N][N];
    int row[N], column[N];
    int b = 1;
    memset(row, 0, sizeof row);
    memset(column, 0, sizeof column);
    for (int i = 1; i <= r; i++) {
      for (int j = 1; j <= c; j++) {
        cin >> a[i][j];
        if (a[i][j] == 'A') {
          cnt++;
          row[i]++;
          column[j]++;
          if (row[i] == c || column[j] == r || i == 1 && j == 1 ||
              i == r && j == c || i == 1 && j == c || i == r && j == 1)
            x++;
        }
      }
    }
    if (cnt == 0) {
      cout << "MORTAL" << endl;
      continue;
    }
    if (cnt == r * c) {
      cout << 0 << endl;
      continue;
    }
    if (column[1] == r || column[c] == r || row[1] == c || row[r] == c) {
      cout << 1 << endl;
      continue;
    }
    if (x) {
      cout << 2 << endl;
      continue;
    }
    if (row[1] > 0 || row[r] > 0 || column[1] > 0 || column[c] > 0) {
      cout << 3 << endl;
      continue;
    }
    cout << 4 << endl;
  }
}
