#include <bits/stdc++.h>
using namespace std;
const long long sz = 1e6 + 5;
char s[66][66];
int main() {
  int t;
  cin >> t;
  while (t--) {
    int r, c;
    scanf("%d %d", &r, &c);
    for (int i = 0; i < r; i++) scanf("%s", s[i]);
    bool yes = 1, no = 1;
    for (int i = 0; i < r; i++) {
      for (int j = 0; j < c; j++) {
        if (s[i][j] == 'P') yes = 0;
        if (s[i][j] == 'A') no = 0;
      }
    }
    if (yes) {
      puts("0");
      continue;
    }
    if (no) {
      puts("MORTAL");
      continue;
    }
    map<int, int> rows, cols;
    for (int i = 0; i < r; i++) {
      bool ok = 1;
      for (int j = 0; j < c; j++) {
        if (s[i][j] == 'P') ok = 0;
      }
      if (ok) rows[i] = 1;
    }
    for (int i = 0; i < c; i++) {
      bool ok = 1;
      for (int j = 0; j < r; j++) {
        if (s[j][i] == 'P') ok = 0;
      }
      if (ok) cols[i] = 1;
    }
    if (rows[0] || cols[0] || rows[r - 1] || cols[c - 1]) {
      puts("1");
      continue;
    }
    for (auto it : rows)
      if (it.second == 1) yes = 1;
    for (auto it : cols)
      if (it.second == 1) yes = 1;
    if (yes) {
      puts("2");
      continue;
    }
    if (s[0][0] == 'A' || s[0][c - 1] == 'A' || s[r - 1][0] == 'A' ||
        s[r - 1][c - 1] == 'A') {
      puts("2");
      continue;
    }
    for (int i = 0; i < r; i++)
      if (s[i][0] == 'A') yes = 1;
    for (int i = 0; i < r; i++)
      if (s[i][c - 1] == 'A') yes = 1;
    for (int i = 0; i < c; i++)
      if (s[0][i] == 'A') yes = 1;
    for (int i = 0; i < c; i++)
      if (s[r - 1][i] == 'A') yes = 1;
    if (yes) {
      puts("3");
      continue;
    }
    puts("4");
  }
}
