#include <bits/stdc++.h>
using namespace std;
int fun() {
  int web[65][65] = {0};
  int n, m;
  scanf("%d %d", &n, &m);
  bool ok1 = false, ok2 = false;
  for (int i = 1; i <= n; i++) {
    char ch = getchar();
    for (int j = 1; j <= m; j++) {
      while (ch != 'A' and ch != 'P') ch = getchar();
      if (ch == 'A') {
        web[i][j] = 1;
        ok1 = true;
      } else
        web[i][j] = 2, ok2 = true;
      ch = getchar();
    }
  }
  if (ok1 == false) {
    printf("MORTAL\n");
    return 0;
  }
  if (ok2 == false) {
    printf("0\n");
    return 0;
  }
  bool sit1 = true, sit2 = false;
  for (int i = 1; i <= m; i++) {
    if (web[1][i] == 2) {
      sit1 = false;
    } else
      sit2 = true;
  }
  if (sit1 == true) {
    printf("1\n");
    return 0;
  }
  sit1 = true;
  for (int i = 1; i <= m; i++) {
    if (web[n][i] == 2) {
      sit1 = false;
    } else
      sit2 = true;
  }
  if (sit1 == true) {
    printf("1\n");
    return 0;
  }
  sit1 = true;
  for (int i = 1; i <= n; i++) {
    if (web[i][1] == 2) {
      sit1 = false;
    } else
      sit2 = true;
  }
  if (sit1 == true) {
    printf("1\n");
    return 0;
  }
  sit1 = true;
  for (int i = 1; i <= n; i++) {
    if (web[i][m] == 2) {
      sit1 = false;
    } else
      sit2 = true;
  }
  if (sit1 == true) {
    printf("1\n");
    return 0;
  }
  if (web[1][1] == 1 or web[1][m] == 1 or web[n][1] == 1 or web[n][m] == 1) {
    printf("2\n");
    return 0;
  }
  if (sit2 == true) {
    bool sit3 = true;
    for (int i = 1; i <= n; i++) {
      sit3 = true;
      for (int j = 1; j <= m; j++) {
        if (web[i][j] == 2) {
          sit3 = false;
          break;
        }
      }
      if (sit3 == true) break;
    }
    if (sit3 == true) {
      printf("2\n");
      return 0;
    }
    for (int i = 1; i <= m; i++) {
      sit3 = true;
      for (int j = 1; j <= n; j++) {
        if (web[j][i] == 2) {
          sit3 = false;
          break;
        }
      }
      if (sit3 == true) break;
    }
    if (sit3 == true) {
      printf("2\n");
      return 0;
    }
    printf("3\n");
    return 0;
  }
  printf("4\n");
  return 0;
}
int main() {
  int t;
  scanf("%d", &t);
  for (int i = 1; i <= t; i++) {
    fun();
  }
  return 0;
}
