#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e2 + 1;
char a[maxn][maxn];
int r[maxn], c[maxn];
int main() {
  int T, n, m, flag, flag1, flag2, left, right, up, down;
  scanf("%d", &T);
  while (T--) {
    flag2 = flag1 = left = right = up = down = flag = 0;
    memset(r, 0, sizeof(r));
    memset(c, 0, sizeof(c));
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; ++i) {
      scanf("%s", a[i] + 1);
      for (int j = 1; j <= m; ++j) {
        r[i] += (a[i][j] == 'A');
        c[j] += (a[i][j] == 'A');
        if (i == 1) up += (a[i][j] == 'A');
        if (i == n) down += (a[i][j] == 'A');
        if (j == 1) left += (a[i][j] == 'A');
        if (j == m) right += (a[i][j] == 'A');
        if (a[i][j] == 'A') flag = 1;
        if (a[i][j] == 'P') flag1 = 1;
      }
    }
    if (!flag1) {
      printf("0\n");
      continue;
    }
    if (!flag) {
      printf("MORTAL\n");
      continue;
    }
    if (left == n || right == n || up == m || down == m) {
      printf("1\n");
      continue;
    }
    for (int i = 1; i <= n; ++i) {
      if (r[i] == m) {
        flag2 = 1;
        break;
      }
    }
    for (int i = 1; i <= m; ++i) {
      if (c[i] == n) {
        flag2 = 1;
        break;
      }
    }
    if (a[1][1] == 'A' || a[1][m] == 'A' || a[n][1] == 'A' || a[n][m] == 'A' ||
        flag2) {
      printf("2\n");
      continue;
    }
    if (left > 0 || right > 0 || up > 0 || down > 0) {
      printf("3\n");
      continue;
    }
    printf("4\n");
  }
}
