#include <bits/stdc++.h>
using namespace std;
const int MOD = 1000000007;
char s[70][70];
int main() {
  int T;
  cin >> T;
  for (int Case = 0; Case < (T); Case++) {
    int h, w;
    scanf("%d%d", &h, &w);
    for (int i = 0; i < (h); i++) scanf("%s", s[i]);
    bool ok = true;
    bool F = false;
    bool t = false;
    for (int i = 0; i < (h); i++)
      for (int j = 0; j < (w); j++) {
        if (s[i][j] == 'P')
          ok = false;
        else
          F = true;
      }
    if (!F) {
      puts("MORTAL");
      goto g;
    }
    if (ok) {
      puts("0");
      goto g;
    }
    ok = true;
    for (int i = 0; i < (h); i++) {
      if (s[i][0] == 'P')
        ok = false;
      else
        t = true;
    }
    if (ok) {
      puts("1");
      goto g;
    }
    ok = true;
    for (int i = 0; i < (h); i++) {
      if (s[i][w - 1] == 'P')
        ok = false;
      else
        t = true;
    }
    if (ok) {
      puts("1");
      goto g;
    }
    ok = true;
    for (int i = 0; i < (w); i++) {
      if (s[0][i] == 'P')
        ok = false;
      else
        t = true;
    }
    if (ok) {
      puts("1");
      goto g;
    }
    ok = true;
    for (int i = 0; i < (w); i++) {
      if (s[h - 1][i] == 'P')
        ok = false;
      else
        t = true;
    }
    if (ok) {
      puts("1");
      goto g;
    }
    if (s[0][0] == 'A' || s[0][w - 1] == 'A' || s[h - 1][0] == 'A' ||
        s[h - 1][w - 1] == 'A') {
      puts("2");
      goto g;
    }
    for (int i = 0; i < (h); i++) {
      bool ok = true;
      for (int j = 0; j < (w); j++) {
        if (s[i][j] == 'P') ok = false;
      }
      if (ok) {
        puts("2");
        goto g;
      }
    }
    for (int i = 0; i < (w); i++) {
      bool ok = true;
      for (int j = 0; j < (h); j++) {
        if (s[j][i] == 'P') ok = false;
      }
      if (ok) {
        puts("2");
        goto g;
      }
    }
    if (t) {
      puts("3");
      goto g;
    }
    puts("4");
  g:;
  }
}
