#include <bits/stdc++.h>
using namespace std;
const int MAX = 66;
char G[MAX][MAX];
int main() {
  int T;
  cin >> T;
  while (T--) {
    int n, m, res = MAX, cnt = 0;
    scanf("%d%d", &n, &m);
    for (int i = 0; i < n; i++) scanf("%s", G[i]);
    for (int i = 0; i < n; i++) {
      bool flag1 = 1, flag2 = 0;
      for (int j = 0; j < m; j++) {
        flag1 &= (G[i][j] == 'A');
        flag2 |= (G[i][j] == 'A');
        cnt += (G[i][j] == 'A');
      }
      if (flag1) {
        if (i == 0 || i == n - 1)
          res = min(res, 1);
        else
          res = min(res, 2);
      } else {
        if (!flag2) continue;
        if (G[i][0] == 'A' || G[i][m - 1] == 'A') {
          if (i == 0 || i == n - 1)
            res = min(res, 2);
          else
            res = min(res, 3);
        } else {
          if (i == 0 || i == n - 1)
            res = min(res, 3);
          else
            res = min(res, 4);
        }
      }
    }
    if (cnt == n * m) {
      printf("0\n");
      continue;
    }
    for (int j = 0; j < m; j++) {
      bool flag1 = 1, flag2 = 0;
      for (int i = 0; i < n; i++) {
        flag1 &= (G[i][j] == 'A');
        flag2 |= (G[i][j] == 'A');
      }
      if (flag1) {
        if (j == 0 || j == m - 1)
          res = min(res, 1);
        else
          res = min(res, 2);
      } else {
        if (!flag2) continue;
        if (G[0][j] == 'A' || G[n - 1][j] == 'A') {
          if (j == 0 || j == m - 1)
            res = min(res, 2);
          else
            res = min(res, 3);
        } else {
          if (j == 0 || j == m - 1)
            res = min(res, 3);
          else
            res = min(res, 4);
        }
      }
    }
    if (res == MAX)
      printf("MORTAL\n");
    else
      printf("%d\n", res);
  }
}
