#include <bits/stdc++.h>
int n, m;
char a[1009][1009];
int lineb[1009];
int linec[1009];
int saracorner;
int paracorner;
void check_corner() {
  if (a[0][0] == 'A') saracorner = 1;
  if (a[n - 1][0] == 'A') saracorner = 1;
  if (a[0][m - 1] == 'A') saracorner = 1;
  if (a[n - 1][m - 1] == 'A') saracorner = 1;
  int i, j, k;
  for (i = 0; i < n; i++) {
    if (a[i][0] == 'A') paracorner = 1;
    if (a[i][m - 1] == 'A') paracorner = 1;
  }
  for (j = 0; j < m; j++) {
    if (a[0][j] == 'A') paracorner = 1;
    if (a[n - 1][j] == 'A') paracorner = 1;
  }
}
void check_line() {
  int i, j, k;
  for (i = 0; i < n; i++) {
    lineb[i] = 0;
    for (j = 0; j < m; j++) {
      if (a[i][j] == 'P') break;
    }
    if (j == m) lineb[i] = 1;
  }
  for (j = 0; j < m; j++) {
    linec[j] = 0;
    for (i = 0; i < n; i++) {
      if (a[i][j] == 'P') break;
    }
    if (i == n) linec[j] = 1;
  }
}
int main() {
  int i, j, k;
  int t, tv = 0;
  scanf("%d", &t);
  while (t--) {
    scanf("%d %d", &n, &m);
    bool noa = true;
    bool nop = true;
    for (i = 0; i < n; i++) {
      scanf("%s", a[i]);
      for (j = 0; j < m; j++) {
        if (a[i][j] == 'A') {
          noa = false;
        }
        if (a[i][j] == 'P') {
          nop = false;
        }
      }
    }
    if (noa) {
      printf("MORTAL\n");
      continue;
    }
    if (nop) {
      printf("0\n");
      continue;
    }
    saracorner = 0;
    paracorner = 0;
    check_corner();
    check_line();
    int res = 4;
    if (lineb[0] || linec[0] || lineb[n - 1] || linec[m - 1]) {
      res = 1;
    } else {
      if (saracorner) {
        res = 2;
      } else {
        for (i = 0; i < n; i++) {
          if (lineb[i]) break;
        }
        if (i < n) {
          res = 2;
        } else {
          for (i = 0; i < m; i++) {
            if (linec[i]) break;
          }
          if (i < m) {
            res = 2;
          } else {
            if (paracorner) {
              res = 3;
            }
          }
        }
      }
    }
    printf("%d\n", res);
  }
}
