#include <bits/stdc++.h>
using namespace std;
char s[100][100];
int n, m;
bool check1() {
  int flag1 = 1, flag2 = 1, flag3 = 1, flag4 = 1;
  for (int i = 0; i < m; i++)
    if (s[0][i] == 'P') flag1 = 0;
  for (int i = 0; i < m; i++)
    if (s[n - 1][i] == 'P') flag2 = 0;
  for (int i = 0; i < n; i++)
    if (s[i][0] == 'P') flag3 = 0;
  for (int i = 0; i < n; i++)
    if (s[i][m - 1] == 'P') flag4 = 0;
  return flag1 || flag2 || flag3 || flag4;
}
bool check2() {
  if (s[0][0] == 'A' || s[0][m - 1] == 'A' || s[n - 1][0] == 'A' ||
      s[n - 1][m - 1] == 'A')
    return 1;
  for (int i = 0; i < n; i++) {
    int flag = 1;
    for (int j = 0; j < m; j++)
      if (s[i][j] == 'P') flag = 0;
    if (flag) return 1;
  }
  for (int j = 0; j < m; j++) {
    int flag = 1;
    for (int i = 0; i < n; i++)
      if (s[i][j] == 'P') flag = 0;
    if (flag) return 1;
  }
  return 0;
}
bool check4() {
  int flag1 = 1, flag2 = 1, flag3 = 1, flag4 = 1;
  for (int i = 0; i < m; i++)
    if (s[0][i] == 'A') flag1 = 0;
  for (int i = 0; i < m; i++)
    if (s[n - 1][i] == 'A') flag2 = 0;
  for (int i = 0; i < n; i++)
    if (s[i][0] == 'A') flag3 = 0;
  for (int i = 0; i < n; i++)
    if (s[i][m - 1] == 'A') flag4 = 0;
  return flag1 && flag2 && flag3 && flag4;
}
int main() {
  int t;
  scanf("%d", &t);
  while (t--) {
    scanf("%d%d", &n, &m);
    for (int i = 0; i < n; i++) scanf("%s", s[i]);
    int flag1 = 0, flag2 = 0;
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        if (s[i][j] == 'A')
          flag1 = 1;
        else
          flag2 = 1;
      }
      if (flag1 && flag2) break;
    }
    if (flag2 == 0)
      cout << 0 << endl;
    else if (flag1 == 0)
      cout << "MORTAL" << endl;
    else {
      if (check1())
        cout << 1 << endl;
      else if (check2())
        cout << 2 << endl;
      else if (check4())
        cout << 4 << endl;
      else
        cout << 3 << endl;
    }
  }
  return 0;
}
