#include <bits/stdc++.h>
using namespace std;
int t, n, m, a[1001][1001];
char s;
int cxk1() {
  int t1 = 0, t2 = 0, t3 = 0, t4 = 0;
  for (int i = 1; i <= n; ++i)
    if (!a[i][1]) t1 = 1;
  for (int i = 1; i <= n; ++i)
    if (!a[i][m]) t2 = 1;
  for (int i = 1; i <= m; ++i)
    if (!a[1][i]) t3 = 1;
  for (int i = 1; i <= m; ++i)
    if (!a[n][i]) t4 = 1;
  if (!t1 || !t2 || !t3 || !t4) return 1;
  return 0;
}
int cxk2() {
  int t1 = 0, t2 = 0, t3 = 0, t4 = 0;
  for (int i = 1; i <= n; ++i)
    if (a[i][1]) t1 = 1;
  for (int i = 1; i <= n; ++i)
    if (a[i][m]) t2 = 1;
  for (int i = 1; i <= m; ++i)
    if (a[1][i]) t3 = 1;
  for (int i = 1; i <= m; ++i)
    if (a[n][i]) t4 = 1;
  if (t1 || t2 || t3 || t4) return 1;
  return 0;
}
int cxk3(int l) {
  int t2 = 0, t4 = 0;
  for (int i = 1; i <= n; ++i)
    if (!a[i][l]) t2 = 1;
  for (int i = 1; i <= m; ++i)
    if (!a[l][i]) t4 = 1;
  if (!t2 || !t4) return 1;
  return 0;
}
void init() {
  int ju = 0;
  cin >> n >> m;
  for (int i = 1; i <= max(n, m); ++i)
    for (int j = 1; j <= max(n, m); ++j) a[i][j] = 0;
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j)
      cin >> s, a[i][j] = (s == 'A' ? 1 : 0), ju += a[i][j];
  if (!ju) {
    puts("MORTAL");
    return;
  }
  if (ju == n * m) {
    puts("0");
    return;
  }
  if (cxk1()) {
    puts("1");
    return;
  }
  if (a[1][1] || a[n][1] || a[1][m] || a[n][m]) {
    puts("2");
    return;
  }
  for (int i = 1; i <= max(n, m); ++i)
    if (cxk3(i)) {
      puts("2");
      return;
    }
  if (cxk2()) {
    puts("3");
    return;
  }
  puts("4");
}
int main() {
  cin >> t;
  while (t--) init();
}
