#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using P = pair<int, int>;
constexpr ld eps = 1e-12;
constexpr int inf = numeric_limits<int>::max() / 2;
constexpr int mod = 1e9 + 7;
template <typename T>
void printv(const vector<T> &v) {
  int sz = v.size();
  for (int i = 0; i < sz; i++) {
    cout << v[i] << " \n"[i == sz - 1];
  }
}
int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  int t;
  cin >> t;
  while (t--) {
    int r, c;
    cin >> r >> c;
    vector<string> s(r);
    bool f1 = false, isAll = true;
    for (int i = 0; i < r; i++) {
      cin >> s[i];
      for (auto x : s[i]) {
        if (x == 'A') f1 = true;
        if (x == 'P') isAll = false;
      }
    }
    if (isAll) {
      cout << 0 << endl;
      continue;
    }
    if (!f1) {
      cout << "MORTAL" << endl;
      continue;
    }
    {
      bool ok1 = true, ok2 = true;
      for (int i = 0; i < r; i++) {
        if (s[i][0] == 'P') ok1 = false;
        if (s[i][c - 1] == 'P') ok2 = false;
      }
      if (ok1 || ok2) {
        cout << 1 << endl;
        continue;
      }
      ok1 = ok2 = true;
      for (int j = 0; j < c; j++) {
        if (s[0][j] == 'P') ok1 = false;
        if (s[r - 1][j] == 'P') ok2 = false;
      }
      if (ok1 || ok2) {
        cout << 1 << endl;
        continue;
      }
    }
    {
      bool ok = (s[0][0] == 'A' || s[r - 1][0] == 'A' || s[0][c - 1] == 'A' ||
                 s[r - 1][c - 1] == 'A');
      if (ok) {
        cout << 2 << endl;
        continue;
      }
      for (int i = 0; i < r; i++) {
        bool f = true;
        for (int j = 0; j < c; j++)
          if (s[i][j] == 'P') f = false;
        if (f) ok = true;
      }
      for (int j = 0; j < c; j++) {
        bool f = true;
        for (int i = 0; i < r; i++)
          if (s[i][j] == 'P') f = false;
        if (f) ok = true;
      }
      if (ok) {
        cout << 2 << endl;
        continue;
      }
    }
    {
      bool ok = false;
      for (int i = 0; i < r; i++) {
        if (s[i][0] == 'A') ok = true;
        if (s[i][c - 1] == 'A') ok = true;
      }
      for (int j = 0; j < c; j++) {
        if (s[0][j] == 'A') ok = true;
        if (s[r - 1][j] == 'A') ok = true;
      }
      if (ok) {
        cout << 3 << endl;
        continue;
      }
    }
    cout << 4 << endl;
  }
}
