#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n, m;
    scanf("%d %d", &n, &m);
    char mmap[80][80];
    for (int i = 0; i <= n - 1; i++) {
      scanf("%s", mmap[i]);
    }
    int cov[80] = {0}, coh[80] = {0};
    bool valid = false;
    int count = 0;
    for (int i = 0; i <= n - 1; i++) {
      for (int j = 0; j <= m - 1; j++) {
        if (mmap[i][j] == 'A') {
          cov[i]++;
          coh[j]++;
          valid = true;
          count++;
        }
      }
    }
    if (count == n * m) {
      printf("0\n");
      continue;
    }
    if (!valid) {
      printf("MORTAL\n");
      continue;
    }
    if (cov[0] == m || cov[n - 1] == m || coh[0] == n || coh[m - 1] == n) {
      printf("1\n");
      continue;
    }
    if (mmap[0][0] == 'A' || mmap[0][m - 1] == 'A' || mmap[n - 1][0] == 'A' ||
        mmap[n - 1][m - 1] == 'A') {
      printf("2\n");
      continue;
    }
    bool found = false;
    for (int i = 1; i < n - 1; i++) {
      if (cov[i] == m) {
        found = true;
        break;
      }
    }
    for (int i = 1; i < m - 1; i++) {
      if (coh[i] == n) {
        found = true;
        break;
      }
    }
    if (found) {
      printf("2\n");
      continue;
    }
    if (cov[0] > 0 || cov[n - 1] > 0 || coh[0] > 0 || coh[m - 1] > 0) {
      printf("3\n");
      continue;
    }
    printf("4\n");
  }
  return 0;
}
