#include <bits/stdc++.h>
using namespace std;
const int maxn = 65;
char g[maxn][maxn];
int r, c, row[maxn], col[maxn];
void solve() {
  memset(row, 0, sizeof row);
  memset(col, 0, sizeof col);
  int sum = 0;
  for (int i = 1; i <= r; i++) {
    for (int j = 1; j <= c; j++) {
      if (g[i][j] == 'A') col[i]++, row[j]++, sum++;
    }
  }
  if (sum == 0)
    printf("MORTAL\n");
  else if (sum == r * c)
    printf("0\n");
  else if (row[1] == r || row[c] == r || col[1] == c || col[r] == c)
    printf("1\n");
  else {
    int flag = 0;
    for (int i = 2; i < r; i++)
      if (col[i] == c) flag = 1;
    for (int i = 2; i < c; i++)
      if (row[i] == r) flag = 1;
    if (flag == 1 || g[1][1] == 'A' || g[r][1] == 'A' || g[1][c] == 'A' ||
        g[r][c] == 'A')
      printf("2\n");
    else if (row[1] > 0 || row[c] > 0 || col[1] > 0 || col[r] > 0)
      printf("3\n");
    else
      printf("4\n");
  }
}
int main() {
  int T;
  scanf("%d", &T);
  while (T--) {
    scanf("%d%d", &r, &c);
    for (int i = 1; i <= r; i++) scanf("%s", g[i] + 1);
    solve();
  }
  return 0;
}
