#include <bits/stdc++.h>
using namespace std;
bitset<50> bit;
const int N = 1e5 + 7;
const int MOD = 1e9 + 7;
const double PI = atan(1.0) * 4;
const int maxn = 3e5 + 5;
int mmp[70][70];
int sum[70];
int sum2[70];
int main() {
  int t;
  scanf("%d", &t);
  while (t--) {
    memset(mmp, 0, sizeof(mmp));
    memset(sum, 0, sizeof(sum));
    memset(sum2, 0, sizeof(sum2));
    int f = 0, f2 = 0, flag = 0;
    int r, c;
    scanf("%d %d", &r, &c);
    for (int i = (1); i <= (r); ++i) {
      char s[70];
      scanf("%s", s + 1);
      for (int j = (1); j <= (c); ++j) {
        if (s[j] == 'A')
          mmp[i][j] = 1;
        else
          mmp[i][j] = 0;
        if (s[j] == 'A') f = 1;
        if (s[j] == 'P') f2 = 1;
      }
    }
    if (!f) {
      cout << "MORTAL" << endl;
      continue;
    }
    if (!f2) {
      printf("%d\n", 0);
      continue;
    }
    for (int i = 1; i <= r; i++) {
      for (int j = 1; j <= c; j++) {
        sum[i] += mmp[i][j];
      }
    }
    for (int i = 1; i <= c; i++) {
      for (int j = 1; j <= r; j++) {
        sum2[i] += mmp[j][i];
      }
    }
    if (sum[1] == c || sum[r] == c || sum2[1] == r || sum2[c] == r) {
      printf("%d\n", 1);
      continue;
    }
    if (mmp[1][1] == 1 || mmp[1][c] == 1 || mmp[r][1] == 1 || mmp[r][c] == 1) {
      printf("%d\n", 2);
      continue;
    }
    for (int i = 1; i <= r; i++) {
      if (sum[i] == c) {
        flag = 1;
        break;
      }
    }
    for (int i = 1; i <= c; i++) {
      if (sum2[i] == r) {
        flag = 1;
        break;
      }
    }
    if (flag) {
      printf("%d\n", 2);
      continue;
    }
    if (sum[1] == 0 && sum[r] == 0 && sum2[1] == 0 && sum2[c] == 0) {
      printf("%d\n", 4);
      continue;
    } else {
      printf("%d\n", 3);
      continue;
    }
  }
  return 0;
}
