#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ii = pair<int, int>;
const int N = 100005;
int main() {
  int t;
  scanf("%d", &t);
  char mat[70][70];
  while (t--) {
    int r, c;
    scanf("%d %d", &r, &c);
    for (int i = 0; i < r; i++) {
      scanf("%s", mat[i]);
    }
    int cnta = 0, cntp = 0;
    for (int i = 0; i < r; i++) {
      for (int j = 0; j < c; j++) {
        cnta += mat[i][j] == 'A';
        cntp += mat[i][j] == 'P';
      }
    }
    if (cnta == 0) {
      printf("MORTAL\n");
    } else if (cntp == 0) {
      printf("0\n");
    } else {
      int r1 = 0, r2 = 0;
      for (int i = 0; i < r; i++) {
        r1 += mat[i][0] == 'A';
        r2 += mat[i][c - 1] == 'A';
      }
      int c1 = 0, c2 = 0;
      for (int i = 0; i < c; i++) {
        c1 += mat[0][i] == 'A';
        c2 += mat[r - 1][i] == 'A';
      }
      if (r1 == r || r2 == r || c1 == c || c2 == c) {
        printf("1\n");
      } else {
        bool da2 = 0;
        for (int i = 0; i < r; i++) {
          int ca = 0;
          for (int j = 0; j < c; j++) {
            ca += mat[i][j] == 'A';
          }
          da2 |= ca == c;
        }
        for (int i = 0; i < c; i++) {
          int ra = 0;
          for (int j = 0; j < r; j++) {
            ra += mat[j][i] == 'A';
          }
          da2 |= ra == r;
        }
        da2 |= mat[0][0] == 'A' || mat[0][c - 1] == 'A' ||
               mat[r - 1][0] == 'A' || mat[r - 1][c - 1] == 'A';
        if (da2) {
          printf("2\n");
        } else {
          bool da3 = 0;
          for (int i = 0; i < r; i++) {
            da3 |= mat[i][0] == 'A';
            da3 |= mat[i][c - 1] == 'A';
          }
          for (int i = 0; i < c; i++) {
            da3 |= mat[0][i] == 'A';
            da3 |= mat[r - 1][i] == 'A';
          }
          if (da3) {
            printf("3\n");
          } else {
            printf("4\n");
          }
        }
      }
    }
  }
  return 0;
}
