#include <bits/stdc++.h>
using namespace std;
int t;
int n, m;
char c[61][61];
void solve() {
  cin >> n >> m;
  bool A = 0, P = 0;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++) {
      cin >> c[i][j];
      if (c[i][j] == 'A')
        A = 1;
      else
        P = 1;
    }
  if (P == 0) {
    cout << 0 << endl;
    return;
  }
  if (A == 0) {
    cout << "MORTAL" << endl;
    return;
  }
  bool s1 = true, s2 = true;
  for (int i = 1; i <= n; i++) {
    if (c[i][1] == 'P') s1 = false;
    if (c[i][m] == 'P') s2 = false;
  }
  if (s1 || s2) {
    cout << 1 << endl;
    return;
  }
  s1 = true, s2 = true;
  for (int i = 1; i <= m; i++) {
    if (c[1][i] == 'P') s1 = false;
    if (c[n][i] == 'P') s2 = false;
  }
  if (s1 || s2) {
    cout << 1 << endl;
    return;
  }
  if (c[1][1] == 'A' || c[1][m] == 'A' || c[n][1] == 'A' || c[n][m] == 'A') {
    cout << 2 << endl;
    return;
  }
  bool suc;
  for (int i = 1; i <= n; i++) {
    suc = true;
    for (int j = 1; j <= m; j++)
      if (c[i][j] == 'P') suc = false;
    if (suc) {
      cout << 2 << endl;
      return;
    }
  }
  for (int i = 1; i <= m; i++) {
    suc = true;
    for (int j = 1; j <= n; j++)
      if (c[j][i] == 'P') suc = false;
    if (suc) {
      cout << 2 << endl;
      return;
    }
  }
  for (int i = 1; i <= n; i++) {
    if (c[i][1] == 'A' || c[i][m] == 'A') {
      cout << 3 << endl;
      return;
    }
  }
  for (int i = 1; i <= m; i++) {
    if (c[1][i] == 'A' || c[n][i] == 'A') {
      cout << 3 << endl;
      return;
    }
  }
  cout << 4 << endl;
  return;
}
int main() {
  cin >> t;
  while (t--) solve();
  return 0;
}
