#include <bits/stdc++.h>
bool f, f1, f2, f3, f4;
char s[66][66];
int n, m;
int main() {
  for (scanf("%*d"); ~scanf("%d%d", &n, &m);) {
    for (int i = 1; i <= n; i++) scanf("%s", s[i] + 1);
    f = 1;
    for (int i = 1; i <= n; i++)
      for (int j = 1; j <= m; j++) f &= s[i][j] == 'P';
    if (f) {
      puts("MORTAL");
      continue;
    }
    f = 1;
    for (int i = 1; i <= n; i++)
      for (int j = 1; j <= m; j++) f &= s[i][j] == 'A';
    if (f) {
      puts("0");
      continue;
    }
    if (n == 1) {
      if (s[1][1] == 'A' || s[1][m] == 'A')
        puts("1");
      else
        puts("2");
      continue;
    }
    if (m == 1) {
      if (s[1][1] == 'A' || s[n][1] == 'A')
        puts("1");
      else
        puts("2");
      continue;
    }
    f1 = f2 = f3 = f4 = 1;
    for (int i = 1; i <= n; i++) {
      f1 &= s[i][1] == 'A';
      f2 &= s[i][m] == 'A';
    }
    for (int i = 1; i <= m; i++) {
      f3 &= s[1][i] == 'A';
      f4 &= s[n][i] == 'A';
    }
    if (f1 || f2 || f3 || f4) {
      puts("1");
      continue;
    }
    for (int i = 1; i <= n; i++) {
      f = 1;
      for (int j = 1; j <= m; j++) f &= s[i][j] == 'A';
      if (f) {
        puts("2");
        goto end;
      }
    }
    for (int i = 1; i <= m; i++) {
      f = 1;
      for (int j = 1; j <= n; j++) f &= s[j][i] == 'A';
      if (f) {
        puts("2");
        goto end;
      }
    }
    if (s[1][1] == 'A' || s[1][m] == 'A' || s[n][1] == 'A' || s[n][m] == 'A') {
      puts("2");
      continue;
    }
    f = 0;
    for (int i = 1; i <= n; i++) f |= s[i][1] == 'A' || s[i][m] == 'A';
    for (int i = 1; i <= m; i++) f |= s[1][i] == 'A' || s[n][i] == 'A';
    if (f) {
      puts("3");
      continue;
    }
    puts("4");
  end:;
  }
}
