#include <bits/stdc++.h>
using namespace std;
char c[61][61];
int sum[61][2];
int main() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n, m;
    scanf("%d %d", &n, &m);
    for (int i = 1; i <= n; i++) scanf("%s", c[i] + 1);
    int tot = 0;
    for (int i = 1; i <= n; i++) sum[i][0] = 0;
    for (int i = 1; i <= m; i++) sum[i][1] = 0;
    for (int i = 1; i <= n; i++)
      for (int j = 1; j <= m; j++) {
        sum[i][0] += (c[i][j] == 'P');
        sum[j][1] += (c[i][j] == 'P');
        tot += (c[i][j] == 'A');
      }
    if (tot == n * m) {
      printf("0\n");
      goto end;
    }
    if (!sum[1][0] || !sum[n][0] || !sum[1][1] || !sum[m][1]) {
      printf("1\n");
      goto end;
    }
    for (int i = 2; i < n; i++)
      if (!sum[i][0]) {
        printf("2\n");
        goto end;
      }
    for (int i = 2; i < m; i++)
      if (!sum[i][1]) {
        printf("2\n");
        goto end;
      }
    if (c[1][1] == 'A' || c[1][m] == 'A' || c[n][1] == 'A' || c[n][m] == 'A') {
      printf("2\n");
      goto end;
    }
    if (sum[1][0] < m || sum[n][0] < m || sum[1][1] < n || sum[m][1] < n) {
      printf("3\n");
      goto end;
    }
    if (tot)
      printf("4\n");
    else
      printf("MORTAL\n");
  end:;
  }
  return 0;
}
