#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
string s[66];
bool check1(int r, int c) {
  bool flag;
  flag = 0;
  for (int i = 0; i < r; i++) {
    if (s[i][0] != 'A') flag = 1;
  }
  if (flag == 0) return true;
  flag = 0;
  for (int i = 0; i < r; i++) {
    if (s[i][c - 1] != 'A') flag = 1;
  }
  if (flag == 0) return true;
  flag = 0;
  for (int i = 0; i < c; i++) {
    if (s[0][i] != 'A') flag = 1;
  }
  if (flag == 0) return true;
  flag = 0;
  for (int i = 0; i < c; i++) {
    if (s[r - 1][i] != 'A') flag = 1;
  }
  if (flag == 0) return true;
  return false;
}
bool check2(int r, int c) {
  bool flag = 0;
  for (int i = 0; i < r; i++) {
    bool ff = 1;
    for (int j = 0; j < c; j++) {
      if (s[i][j] != 'A') ff = 0;
    }
    flag |= ff;
  }
  for (int j = 0; j < c; j++) {
    bool ff = 1;
    for (int i = 0; i < r; i++) {
      if (s[i][j] != 'A') ff = 0;
    }
    flag |= ff;
  }
  return flag || s[0][0] == 'A' || s[0][c - 1] == 'A' || s[r - 1][0] == 'A' ||
         s[r - 1][c - 1] == 'A';
}
bool check3(int r, int c) {
  bool flag;
  flag = 0;
  for (int i = 0; i < r; i++) {
    if (s[i][0] == 'A') flag = 1;
  }
  for (int i = 0; i < r; i++) {
    if (s[i][c - 1] == 'A') flag = 1;
  }
  for (int i = 0; i < c; i++) {
    if (s[0][i] == 'A') flag = 1;
  }
  for (int i = 0; i < c; i++) {
    if (s[r - 1][i] == 'A') flag = 1;
  }
  return flag;
}
int main() {
  int t;
  cin >> t;
  while (t--) {
    int r, c;
    cin >> r >> c;
    bool flag = 0, ff = 0;
    for (int i = 0; i < r; i++) {
      cin >> s[i];
      for (auto ch : s[i]) {
        if (ch != 'A') flag = 1;
        if (ch != 'P') ff = 1;
      }
    }
    if (ff == 0) {
      puts("MORTAL");
    } else if (flag == 0) {
      puts("0");
    } else if (check1(r, c)) {
      puts("1");
    } else if (check2(r, c)) {
      puts("2");
    } else if (check3(r, c)) {
      puts("3");
    } else
      puts("4");
  }
  return 0;
}
