#include <bits/stdc++.h>
using namespace std;
template <class t>
inline t read(t &x) {
  x = 0;
  char c = getchar();
  bool f = 0;
  while (!isdigit(c)) f |= c == '-', c = getchar();
  while (isdigit(c)) x = (x << 1) + (x << 3) + (c ^ 48), c = getchar();
  if (f) x = -x;
  return x;
}
template <class t>
inline void write(t x) {
  if (x < 0) {
    putchar('-'), write(-x);
  } else {
    if (x > 9) write(x / 10);
    putchar('0' + x % 10);
  }
}
const int N = 65;
char a[N][N];
void doit() {
  int n, m;
  bool flaga = 1, flagp = 1, flagl = 0, flagc = 0, flagll = 0, flagcc = 0,
       flage = 0;
  read(n);
  read(m);
  for (int i = 1; i <= n; i++) scanf("%s", a[i] + 1);
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      if (a[i][j] == 'A')
        flagp = 0;
      else
        flaga = 0;
    }
  }
  if (flaga) {
    puts("0");
    return;
  }
  if (flagp) {
    puts("MORTAL");
    return;
  }
  for (int i = 1; i <= n; i++) {
    bool cur = 1;
    for (int j = 1; j <= m; j++)
      if (a[i][j] == 'P') {
        cur = 0;
        break;
      }
    if (cur) flagl = 1, flagll |= (i == 1 || i == n);
  }
  for (int i = 1; i <= m; i++) {
    bool cur = 1;
    for (int j = 1; j <= n; j++)
      if (a[j][i] == 'P') {
        cur = 0;
        break;
      }
    if (cur) flagc = 1, flagcc |= (i == 1 || i == m);
  }
  if (flagll || flagcc) {
    puts("1");
    return;
  }
  if (flagl || flagc) {
    puts("2");
    return;
  }
  if (a[1][1] == 'A' || a[n][1] == 'A' || a[1][m] == 'A' || a[n][m] == 'A') {
    puts("2");
    return;
  }
  for (int i = 1; i <= m; i++)
    if (a[1][i] == 'A' || a[n][i] == 'A') flage = 1;
  for (int i = 1; i <= n; i++)
    if (a[i][1] == 'A' || a[i][m] == 'A') flage = 1;
  if (flage) {
    puts("3");
  } else {
    puts("4");
  }
}
signed main() {
  int t;
  read(t);
  while (t--) doit();
}
