#include <bits/stdc++.h>
using namespace std;
const int N = 65;
char a[N][N];
int s[N][N];
int r, c;
int area(int x, int y, int u, int v) {
  return s[u][v] - s[x - 1][v] - s[u][y - 1] + s[x - 1][y - 1];
}
void solve() {
  cin >> r >> c;
  memset(s, 0, sizeof(s));
  for (int i = 1; i <= r; ++i) {
    getchar();
    for (int j = 1; j <= c; ++j) {
      a[i][j] = getchar();
      s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + (a[i][j] == 'A');
    }
  }
  if (area(1, 1, r, c) == r * c) {
    puts("0");
    return;
  }
  if (area(1, 1, r, c) == 0) {
    puts("MORTAL");
    return;
  }
  if (area(1, 1, 1, c) == c || area(r, 1, r, c) == c || area(1, 1, r, 1) == r ||
      area(1, c, r, c) == r) {
    puts("1");
    return;
  }
  for (int i = 2; i < r; ++i) {
    if (area(i, 1, i, c) == c) {
      puts("2");
      return;
    }
  }
  for (int i = 2; i < c; ++i) {
    if (area(1, i, r, i) == r) {
      puts("2");
      return;
    }
  }
  if (a[1][1] == 'A' || a[1][c] == 'A' || a[r][1] == 'A' || a[r][c] == 'A') {
    puts("2");
    return;
  }
  for (int i = 2; i < r; ++i) {
    if (a[i][1] == 'A' || a[i][c] == 'A') {
      puts("3");
      return;
    }
  }
  for (int i = 2; i < c; ++i) {
    if (a[1][i] == 'A' || a[r][i] == 'A') {
      puts("3");
      return;
    }
  }
  puts("4");
}
int main() {
  int nT;
  cin >> nT;
  while (nT--) solve();
}
