#include <bits/stdc++.h>
using namespace std;
#pragma GCC diagnostic ignored "-Wmissing-declarations"
char a[70][70];
void solve() {
  int rows, cols;
  cin >> rows >> cols;
  for (int r = 0; r < rows; ++r) cin >> a[r];
  bool haveA = false;
  bool haveP = false;
  for (int r = 0; r < rows; ++r)
    for (int c = 0; c < cols; ++c) {
      haveA |= a[r][c] == 'A';
      haveP |= a[r][c] == 'P';
    }
  if (!haveA) {
    cout << "MORTAL\n";
    return;
  }
  if (!haveP) {
    cout << "0\n";
    return;
  }
  int best = 4;
  if (a[0][0] == 'A' || a[rows - 1][0] == 'A' || a[0][cols - 1] == 'A' ||
      a[rows - 1][cols - 1] == 'A')
    best = 2;
  for (int r = 0; r < rows; ++r) {
    haveA = false;
    haveP = false;
    for (int c = 0; c < cols; ++c) {
      haveA |= a[r][c] == 'A';
      haveP |= a[r][c] == 'P';
    }
    if (!haveP) best = min(best, (r == 0 || r == rows - 1) ? 1 : 2);
    if (haveA) best = min(best, (r == 0 || r == rows - 1) ? 3 : 4);
  }
  for (int c = 0; c < cols; ++c) {
    haveA = false;
    haveP = false;
    for (int r = 0; r < rows; ++r) {
      haveA |= a[r][c] == 'A';
      haveP |= a[r][c] == 'P';
    }
    if (!haveP) best = min(best, (c == 0 || c == cols - 1) ? 1 : 2);
    if (haveA) best = min(best, (c == 0 || c == cols - 1) ? 3 : 4);
  }
  cout << best << '\n';
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0), cout.tie(0);
  int t;
  cin >> t;
  while (t--) solve();
}
