#include <bits/stdc++.h>
using namespace std;
int dp[100][20] = {0};
const int maxx = 1e3 + 2;
char a[maxx][maxx];
long long b[maxx];
const long long mod = 1e9 + 7;
int main() {
  long long t, i, j, k, n, m;
  cin >> t;
  while (t--) {
    cin >> n >> m;
    for (i = 0; i < n; i++) scanf("%s", a[i]);
    long long ans = 0;
    for (i = 0; i < n; i++)
      for (j = 0; j < m; j++) {
        if (a[i][j] == 'A') ans++;
      }
    if (ans == n * m) {
      printf("0\n");
      continue;
    }
    if (ans == 0) {
      printf("MORTAL\n");
      continue;
    }
    if (n == 1) {
      if (a[0][0] == 'A' || a[0][m - 1] == 'A')
        printf("1\n");
      else
        printf("2\n");
      continue;
    }
    if (m == 1) {
      if (a[0][0] == 'A' || a[n - 1][0] == 'A')
        printf("1\n");
      else
        printf("2\n");
      continue;
    }
    int flag1 = 0, flag2 = 0, flag3 = 0;
    for (i = 0; i < n; i++) {
      int biaoji = 1;
      for (j = 0; j < m; j++) {
        if (a[i][j] != 'A') {
          biaoji = 0;
        }
      }
      if (biaoji == 1) {
        if (i == 0 || i == (n - 1))
          flag1 = 1;
        else
          flag2 = 1;
      }
    }
    for (i = 0; i < m; i++) {
      int biaoji = 1;
      for (j = 0; j < n; j++) {
        if (a[j][i] != 'A') {
          biaoji = 0;
        }
      }
      if (biaoji == 1) {
        if (i == 0 || i == (m - 1))
          flag1 = 1;
        else
          flag2 = 1;
      }
    }
    if (a[0][0] == 'A' || a[0][m - 1] == 'A' || a[n - 1][0] == 'A' ||
        a[n - 1][m - 1] == 'A')
      flag2 = 1;
    for (i = 0; i < n; i++) {
      if (a[i][0] == 'A' || a[i][m - 1] == 'A') flag3 = 1;
    }
    for (i = 0; i < m; i++) {
      if (a[0][i] == 'A' || a[n - 1][i] == 'A') flag3 = 1;
    }
    if (flag1 == 1)
      printf("1\n");
    else if (flag2 == 1)
      printf("2\n");
    else if (flag3 == 1)
      printf("3\n");
    else
      printf("4\n");
  }
  return 0;
}
