#include <bits/stdc++.h>
using namespace std;
const long long int mod = 998244353;
const long double error = 2e-6;
const long double PI = acosl(-1);
inline long long int MOD(long long int x, long long int m = mod) {
  long long int y = x % m;
  return (y >= 0) ? y : y + m;
}
const int inf = 1e9;
const long long int infl = 1061109567;
const int nmax = 1000 + 10;
int ot = 3600;
vector<string> str, str1;
int r, c;
void koto() {
  int i, j;
  string f1 = str[0], f2 = str[r - 1], f3 = str1[0], f4 = str1[c - 1];
  string m1 = "", m2 = "";
  for (i = 0; i < r; i++) m2 += 'A';
  for (i = 0; i < c; i++) m1 += 'A';
  if (f1 == m1 or f2 == m1 or f3 == m2 or f4 == m2) {
    ot = 1;
    return;
  }
  if (f1[0] == 'A' or f1[c - 1] == 'A' or f2[0] == 'A' or f2[c - 1] == 'A') {
    ot = 2;
    return;
  }
  for (i = 0; i < r; i++) {
    string xx = str[i];
    if (xx == m1) {
      ot = 2;
      return;
    }
  }
  for (i = 0; i < c; i++) {
    string xx = str1[i];
    if (xx == m2) {
      ot = 2;
      return;
    }
  }
  for (i = 1; i < c - 1; i++) {
    if (f1[i] == 'A' or f2[i] == 'A') {
      ot = 3;
      return;
    }
  }
  for (i = 1; i < r - 1; i++) {
    if (f3[i] == 'A' or f4[i] == 'A') {
      ot = 3;
      return;
    }
  }
  ot = 4;
  return;
}
void solve() {
  str.clear();
  str1.clear();
  int i, j;
  cin >> r >> c;
  int cna = 0;
  for (i = 0; i < r; i++) {
    string xx;
    cin >> xx;
    str.push_back(xx);
    if (i == 0) {
      for (j = 0; j < xx.size(); j++) {
        string ffk = "0";
        ffk[0] = xx[j];
        str1.push_back(ffk);
        if (ffk == "A") cna++;
      }
    } else {
      for (j = 0; j < xx.size(); j++) {
        str1[j] += xx[j];
        if (xx[j] == 'A') cna++;
      }
    }
  }
  if (cna == 0) {
    cout << "MORTAL" << endl;
    return;
  }
  if (cna == r * c) {
    cout << 0 << endl;
    return;
  }
  koto();
  int pt = ot;
  ot = 3600;
  cout << pt << endl;
}
int main() {
  int t;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
