#include <bits/stdc++.h>
using namespace std;
const string nl = "\n";
const long long MOD = 1000000007;
const long long ARR_MAX = 1e5 + 1;
void solve() {
  int r, c;
  cin >> r >> c;
  string s[r];
  bool hasA = false, hasP = false;
  for (int i = 0; i < r; i++) {
    cin >> s[i];
    for (int j = 0; j < c; j++) {
      if (s[i][j] == 'P') {
        hasP = true;
      } else {
        hasA = true;
      }
    }
  }
  if (!hasA) {
    cout << "MORTAL" << nl;
    return;
  }
  if (!hasP) {
    cout << 0 << nl;
    return;
  }
  int flag = 0;
  int dx[4] = {0, 0, 1, 1}, dy[4] = {1, 1, 0, 0}, ix[4] = {0, r - 1, 0, 0},
      iy[4] = {0, 0, 0, c - 1}, lim[4] = {c, c, r, r};
  for (int i = 0; i < 4; i++) {
    int x = ix[i], y = iy[i];
    flag = 1;
    for (int j = 0; j < lim[i]; j++) {
      x = ix[i] + j * dx[i];
      y = iy[i] + j * dy[i];
      if (s[x][y] == 'P') {
        flag = 0;
        break;
      }
    }
    if (flag == 1) {
      cout << 1 << nl;
      return;
    }
  }
  if (s[0][0] == 'A' || s[0][c - 1] == 'A' || s[r - 1][0] == 'A' ||
      s[r - 1][c - 1] == 'A') {
    cout << 2 << nl;
    return;
  }
  for (int i = 0; i < r; i++) {
    int flag = 1;
    for (int j = 0; j < c; j++) {
      if (s[i][j] == 'P') flag = 0;
    }
    if (flag) {
      cout << 2 << nl;
      return;
    }
  }
  for (int j = 0; j < c; j++) {
    int flag = 1;
    for (int i = 0; i < r; i++) {
      if (s[i][j] == 'P') flag = 0;
    }
    if (flag) {
      cout << 2 << nl;
      return;
    }
  }
  for (int i = 0; i < r; i++) {
    if (s[i][0] == 'A' || s[i][c - 1] == 'A') {
      cout << 3 << nl;
      return;
    }
  }
  for (int i = 0; i < c; i++) {
    if (s[0][i] == 'A' || s[r - 1][i] == 'A') {
      cout << 3 << nl;
      return;
    }
  }
  cout << 4 << nl;
}
int main() {
  int t = 1;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
