#include <bits/stdc++.h>
using namespace std;
void err(istream_iterator<string> it) {}
template <typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
  cerr << *it << " = " << a << endl;
  err(++it, args...);
}
template <typename... T>
void rd(T&... args) {
  ((cin >> args), ...);
}
template <typename... T>
void ps(T... args) {
  ((cout << args << ' '), ...);
  cout << '\n';
}
const long long MOD = 1e9 + 7, MOD1 = 998244353LL, MAX = 1e5 + 5;
const char nl = '\n';
const int INF = 2e9;
int n, m;
char s[61][61];
void solve() {
  cin >> n >> m;
  bool fe = 0, fe1 = 0, fe2 = 0;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) {
      cin >> s[i][j];
      if (s[i][j] == 'A')
        fe1 = 1;
      else
        fe2 = 1;
    }
  if (!fe1) {
    cout << "MORTAL\n";
    return;
  }
  if (!fe2) {
    cout << "0\n";
    return;
  }
  for (int i = 0; i < m; i++) {
    if (s[0][i] == 'P')
      fe1 = 0;
    else
      fe = 1;
    if (s[n - 1][i] == 'P')
      fe2 = 0;
    else
      fe = 1;
  }
  if (fe1 || fe2) {
    cout << "1\n";
    return;
  }
  fe1 = 1, fe2 = 1;
  for (int i = 0; i < n; i++) {
    if (s[i][0] == 'P')
      fe1 = 0;
    else
      fe = 1;
    if (s[i][m - 1] == 'P')
      fe2 = 0;
    else
      fe = 1;
  }
  if (fe1 || fe2) {
    cout << "1\n";
    return;
  }
  for (int i = 1; i < n - 1; i++) {
    bool bad = 0;
    for (int j = 0; j < m; j++) {
      if (s[i][j] == 'P') {
        bad = 1;
        break;
      }
    }
    if (bad) continue;
    cout << "2\n";
    return;
  }
  for (int i = 1; i < m - 1; i++) {
    bool bad = 0;
    for (int j = 0; j < n; j++) {
      if (s[j][i] == 'P') {
        bad = 1;
        break;
      }
    }
    if (bad) continue;
    cout << "2\n";
    return;
  }
  if (s[0][0] == 'A' || s[0][m - 1] == 'A' || s[n - 1][m - 1] == 'A' ||
      s[n - 1][0] == 'A') {
    cout << "2\n";
    return;
  }
  if (fe) {
    cout << "3\n";
    return;
  }
  cout << "4\n";
  return;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  int __;
  cin >> __;
  while (__--) {
    solve();
  }
  return 0;
}
