#include <bits/stdc++.h>
using namespace std;
long long n, m, x, i, j, k, a, t;
int main() {
  cin >> t;
  while (t--) {
    cin >> n >> m;
    string s[n];
    int rows[n], cols[m];
    memset(rows, 0, sizeof rows);
    memset(cols, 0, sizeof cols);
    a = 0;
    for (i = 0; i < n; i++) {
      cin >> s[i];
      for (j = 0; j < m; j++) {
        if (s[i].at(j) == 'A') {
          rows[i]++;
          cols[j]++;
          a++;
        }
      }
    }
    if (a == 0) {
      cout << "MORTAL\n";
      continue;
    }
    if (a == n * m) {
      cout << "0\n";
      continue;
    }
    if (rows[0] == m || rows[n - 1] == m || cols[0] == n || cols[m - 1] == n) {
      cout << "1\n";
      continue;
    }
    bool dos = false, tres = false;
    for (j = 0; j < n; j++) {
      if (rows[j] == m)
        dos = true;
      else if (j > 0 && j < n - 1 &&
               (s[j].at(0) == 'A' || s[j].at(m - 1) == 'A'))
        tres = true;
      else if (s[j].at(0) == 'A' || s[j].at(m - 1) == 'A')
        dos = true;
    }
    for (j = 0; j < m; j++) {
      if (cols[j] == n)
        dos = true;
      else if (j > 0 && j < m - 1 &&
               (s[0].at(j) == 'A' || s[n - 1].at(j) == 'A'))
        tres = true;
      else if (s[0].at(j) == 'A' || s[n - 1].at(j) == 'A')
        dos = true;
    }
    if (dos) {
      cout << "2\n";
      continue;
    } else if (tres) {
      cout << "3\n";
      continue;
    } else {
      cout << "4\n";
    }
  }
}
