#include <bits/stdc++.h>
inline long long read() {
  long long x = 0;
  char c = getchar(), f = 1;
  for (; c < '0' || '9' < c; c = getchar())
    if (c == '-') f = -1;
  for (; '0' <= c && c <= '9'; c = getchar()) x = x * 10 + c - '0';
  return x * f;
}
inline void write(long long x) {
  static char buf[20];
  int len = 0;
  if (x < 0) putchar('-'), x = -x;
  for (; x; x /= 10) buf[len++] = x % 10 + '0';
  if (!len)
    putchar('0');
  else
    while (len) putchar(buf[--len]);
}
inline void writesp(long long x) {
  write(x);
  putchar(' ');
}
inline void writeln(long long x) {
  write(x);
  putchar('\n');
}
char mp[2010][2010];
int n, m;
void work() {
  n = read();
  m = read();
  for (int i = 1; i <= n; i++) scanf("%s", mp[i] + 1);
  int cnt = 0;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++)
      if (mp[i][j] == 'A') ++cnt;
  if (cnt == n * m) {
    puts("0");
    return;
  }
  if (!cnt) {
    puts("MORTAL");
    return;
  }
  int flag0 = 1, flag1 = 1, flag2 = 1, flag3 = 1;
  for (int i = 1; i <= n; i++)
    flag0 &= (mp[i][1] == 'A'), flag1 &= (mp[i][m] == 'A');
  for (int i = 1; i <= m; i++)
    flag2 &= (mp[1][i] == 'A'), flag3 &= (mp[n][i] == 'A');
  if (flag0 || flag1 || flag2 || flag3) {
    puts("1");
    return;
  }
  if (mp[1][1] == 'A' || mp[n][1] == 'A' || mp[1][m] == 'A' ||
      mp[n][m] == 'A') {
    puts("2");
    return;
  }
  for (int i = 1; i <= n; i++) {
    int flag = 1;
    for (int j = 1; j <= m; j++) flag &= (mp[i][j] == 'A');
    if (flag) {
      puts("2");
      return;
    }
  }
  for (int j = 1; j <= m; j++) {
    int flag = 1;
    for (int i = 1; i <= n; i++) flag &= (mp[i][j] == 'A');
    if (flag) {
      puts("2");
      return;
    }
  }
  int flag = 0;
  for (int i = 1; i <= n; i++) flag |= (mp[i][1] == 'A') | (mp[i][m] == 'A');
  for (int i = 1; i <= m; i++) flag |= (mp[1][i] == 'A') | (mp[n][i] == 'A');
  if (flag) {
    puts("3");
    return;
  }
  puts("4");
}
int main() {
  int T = read();
  while (T--) work();
  return 0;
}
