#include <bits/stdc++.h>
using namespace std;
using int64 = long long;
constexpr int DEBUG = 0;
template <class T>
inline bool UpdateMin(T& a, T b) {
  if (a > b) {
    a = b;
    return 1;
  }
  return 0;
}
template <class T>
inline bool UpdateMax(T& a, T b) {
  if (a < b) {
    a = b;
    return 1;
  }
  return 0;
}
void SolveCase() {
  int h, w;
  cin >> h >> w;
  vector<string> board(h);
  for (int i = 0; i < h; i++) {
    cin >> board[i];
  }
  bool has_a = false;
  bool has_p = false;
  for (int y = 0; y < h; y++) {
    for (int x = 0; x < w; x++) {
      if (board[y][x] == 'A') {
        has_a = true;
      } else {
        has_p = true;
      }
    }
  }
  if (!has_a) {
    cout << "MORTAL" << endl;
    return;
  }
  if (!has_p) {
    cout << 0 << endl;
    return;
  }
  int ans = 4;
  for (int y = 0; y < h; y++) {
    bool all_a = true;
    for (int x = 0; x < w; x++) {
      if (board[y][x] != 'A') all_a = false;
    }
    if (all_a) {
      if (y == 0 || y == h - 1)
        UpdateMin(ans, 1);
      else
        UpdateMin(ans, 2);
    }
  }
  for (int x = 0; x < w; x++) {
    bool all_a = true;
    for (int y = 0; y < h; y++) {
      if (board[y][x] != 'A') all_a = false;
    }
    if (all_a) {
      if (x == 0 || x == w - 1)
        UpdateMin(ans, 1);
      else
        UpdateMin(ans, 2);
    }
  }
  for (int y = 0; y < h; y++) {
    for (int x = 0; x < w; x++) {
      if (board[y][x] != 'A') continue;
      bool y_edge = (y == 0 || y == h - 1);
      bool x_edge = (x == 0 || x == w - 1);
      if (y_edge && x_edge) {
        UpdateMin(ans, 2);
      } else if (y_edge || x_edge) {
        UpdateMin(ans, 3);
      }
    }
  }
  cout << ans << endl;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int num_cases;
  cin >> num_cases;
  for (int i = 0; i < num_cases; i++) {
    SolveCase();
  }
}
