#include <bits/stdc++.h>
using namespace std;
int Ttest, n, m;
int s1[1000], s2[1000], s;
string a[1000];
int main() {
  cin >> Ttest;
  while (Ttest--) {
    cin >> n >> m;
    s = 0;
    for (int i = 1; i <= n; i++) s1[i] = 0;
    for (int i = 1; i <= m; i++) s2[i] = 0;
    for (int i = 1; i <= n; i++) {
      cin >> a[i];
      a[i] = "#" + a[i];
      for (int j = 1; j <= m; j++)
        if (a[i][j] == 'A') {
          s1[i]++;
          s2[j]++;
          s++;
        }
    }
    int kq = 10;
    if ((s1[1] == m) || (s2[1] == n) || (s1[n] == m) || (s2[m] == n)) {
      kq = 1;
    } else if ((a[1][1] == 'A') || (a[1][m] == 'A') || (a[n][1] == 'A') ||
               (a[n][m] == 'A')) {
      kq = 2;
    } else if ((s1[1] > 0) || (s2[1] > 0) || (s1[n] > 0) || (s2[m] > 0)) {
      kq = 3;
    } else if (s > 0)
      kq = 4;
    for (int i = 1; i <= n; i++)
      if (s1[i] == m) kq = min(kq, 2);
    for (int i = 1; i <= m; i++)
      if (s2[i] == n) kq = min(kq, 2);
    if (s == n * m) kq = 0;
    if (kq > 4)
      cout << "MORTAL" << endl;
    else
      cout << kq << endl;
  }
  return 0;
}
