#include <bits/stdc++.h>
using namespace std;
int r, c;
char s1[70][70];
int colCheck(int still, int choice) {
  int cc = 0;
  if (choice == 1) {
    for (int i = 0; i < r; i++) {
      if (s1[i][still] != 'A') return 0;
    }
    return 1;
  } else {
    for (int i = 1; i < c - 1; i++) {
      if (s1[0][i] == 'A' || s1[r - 1][i] == 'A') return 1;
    }
    return 0;
  }
}
int rowCheck(int still, int choice) {
  int cc = 0;
  if (choice == 1) {
    for (int i = 0; i < c; i++) {
      if (s1[still][i] != 'A') return 0;
    }
    return 1;
  } else {
    for (int i = 1; i < r - 1; i++) {
      if (s1[i][0] == 'A' || s1[i][c - 1] == 'A') return 1;
    }
    return 0;
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int t;
  cin >> t;
  while (t--) {
    cin >> r >> c;
    memset(s1, '\0', sizeof s1);
    for (int i = 0; i < r; i++) cin >> s1[i];
    bool aa = 0, pp = 0;
    for (int i = 0; i < r; i++) {
      for (int j = 0; j < c; j++) {
        if (s1[i][j] == 'A') aa = 1;
        if (s1[i][j] == 'P') pp = 1;
      }
    }
    if (!aa) {
      cout << "MORTAL\n";
      continue;
    }
    if (!pp) {
      cout << "0\n";
      continue;
    }
    if (rowCheck(0, 1) || rowCheck(r - 1, 1) || colCheck(0, 1) ||
        colCheck(c - 1, 1)) {
      cout << 1 << "\n";
      continue;
    }
    if (s1[0][0] == 'A' || s1[0][c - 1] == 'A' || s1[r - 1][0] == 'A' ||
        s1[r - 1][c - 1] == 'A') {
      cout << 2 << "\n";
      continue;
    }
    bool ok = 0;
    for (int i = 1; i < r - 1; i++) {
      if (rowCheck(i, 1)) {
        cout << "2\n";
        ok = 1;
        break;
      }
    }
    if (ok) continue;
    for (int i = 1; i < c - 1; i++) {
      if (colCheck(i, 1)) {
        cout << "2\n";
        ok = 1;
        break;
      }
    }
    if (ok) continue;
    if (rowCheck(0, 2) || colCheck(0, 2)) {
      cout << "3\n";
      ok = 1;
    }
    if (ok) continue;
    cout << "4\n";
  }
  return 0;
}
