#include <bits/stdc++.h>
using namespace std;
char maps[100][100];
int main() {
  int i, n, m, j, k, l, t, p, mods = 1e9 + 7;
  scanf("%d", &t);
  while (t--) {
    scanf("%d", &n);
    scanf("%d", &m);
    for (i = 0; i < n; i++) scanf("%s", maps[i]);
    k = 0;
    for (i = 0; i < n; i++)
      for (j = 0; j < m; j++) {
        if (maps[i][j] == 'A') k++;
      }
    if (k == 0) {
      printf("MORTAL\n");
      continue;
    }
    if (k == m * n) {
      printf("0\n");
      continue;
    }
    for (i = 0; i < n; i++)
      if (maps[i][0] == 'P') break;
    if (i >= n) {
      printf("1\n");
      continue;
    }
    for (i = 0; i < n; i++)
      if (maps[i][m - 1] == 'P') break;
    if (i >= n) {
      printf("1\n");
      continue;
    }
    for (j = 0; j < m; j++)
      if (maps[0][j] == 'P') break;
    if (j >= m) {
      printf("1\n");
      continue;
    }
    for (j = 0; j < m; j++)
      if (maps[n - 1][j] == 'P') break;
    if (j >= m) {
      printf("1\n");
      continue;
    }
    if (maps[0][0] == 'A' || maps[n - 1][0] == 'A' || maps[0][m - 1] == 'A' ||
        maps[n - 1][m - 1] == 'A') {
      printf("2\n");
      continue;
    }
    for (i = 0; i < n; i++) {
      k = 0;
      for (j = 0; j < m; j++) {
        if (maps[i][j] == 'A') k++;
      }
      if (k >= m) break;
    }
    if (k >= m) {
      printf("2\n");
      continue;
    }
    for (j = 0; j < m; j++) {
      k = 0;
      for (i = 0; i < n; i++) {
        if (maps[i][j] == 'A') k++;
      }
      if (k >= n) break;
    }
    if (k >= n) {
      printf("2\n");
      continue;
    }
    k = 0;
    for (i = 0; i < n; i++)
      if (maps[i][0] == 'A') k++;
    for (i = 0; i < n; i++)
      if (maps[i][m - 1] == 'A') k++;
    for (j = 0; j < m; j++)
      if (maps[0][j] == 'A') k++;
    for (j = 0; j < m; j++)
      if (maps[n - 1][j] == 'A') k++;
    if (k > 0) {
      printf("3\n");
      continue;
    }
    printf("4\n");
    continue;
  }
  return 0;
}
