#include <bits/stdc++.h>
using namespace std;
const int maxr = 60 + 50;
signed main() {
  int T;
  scanf("%d", &T);
  while (T--) {
    int r, c;
    scanf("%d%d", &r, &c);
    bool fPa = 1, fAa = 1, tagj = 0, tagb = 0, tagd = 0;
    bool tagh[maxr], tagl[maxr];
    for (register int i = 1; i <= maxr; ++i) tagh[i] = tagl[i] = true;
    for (register int i = 1; i <= r; ++i)
      for (register int j = 1; j <= c; ++j) {
        char ch;
        cin >> ch;
        if (ch == 'A') {
          fPa = false;
          if (i == 1 && j == 1 || i == r && j == 1 || i == 1 && j == c ||
              i == r && j == c)
            tagj = 1;
          else if (i == 1 && j != 1 && j != c || i == r && j != 1 && j != c ||
                   j == 1 && i != 1 && i != r || j == c && i != 1 && i != r)
            tagb = 1;
          else
            tagd = 1;
        }
        if (ch == 'P') {
          fAa = false;
          tagh[i] = false;
          tagl[j] = false;
        }
      }
    if (fPa)
      printf("MORTAL\n");
    else if (fAa)
      printf("0\n");
    else if (tagh[1] || tagh[r] || tagl[1] || tagl[c])
      printf("1\n");
    else {
      if (tagj)
        printf("2\n");
      else {
        bool FLAG = 0;
        for (register int i = 2; i < r; ++i)
          if (tagh[i]) FLAG = 1;
        for (register int i = 2; i < c; ++i)
          if (tagl[i]) FLAG = 1;
        if (FLAG)
          printf("2\n");
        else if (tagb)
          printf("3\n");
        else if (tagd)
          printf("4\n");
      }
    }
  }
  return 0;
}
