#include <bits/stdc++.h>
using namespace std;
template <typename T>
bool mmax(T &m, const T q) {
  if (m < q) {
    m = q;
    return true;
  } else
    return false;
}
template <typename T>
bool mmin(T &m, const T q) {
  if (m > q) {
    m = q;
    return true;
  } else
    return false;
}
template <typename T>
T add(T &a, T b) {
  return (a += b) %= 1000000007;
}
template <typename T>
T sub(T &a, T b) {
  (a -= b);
  if (a < 0) a += 1000000007;
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long T;
  cin >> T;
  while (T--) {
    long long n, m;
    cin >> n >> m;
    string s[n];
    for (long long i = 0; i < n; i++) {
      cin >> s[i];
    }
    long long fa = 0, fp = 0;
    for (long long i = 0; i < n; i++) {
      for (long long j = 0; j < m; j++) {
        if (s[i][j] == 'A')
          fa = 1;
        else
          fp = 1;
      }
    }
    if (fp == 0) {
      cout << 0 << "\n";
      continue;
    }
    if (fa == 0) {
      cout << "MORTAL"
           << "\n";
      continue;
    }
    string mm = "";
    for (long long i = 0; i < m; i++) mm += "A";
    if (s[0] == mm || s[n - 1] == mm) {
      cout << 1 << "\n";
      continue;
    }
    string s1 = "", s2 = "";
    mm = "";
    for (long long i = 0; i < n; i++) mm += "A";
    for (long long i = 0; i < n; i++) {
      s1 += s[i][0];
      s2 += s[i][m - 1];
    }
    if (s1 == mm || s2 == mm) {
      cout << 1 << "\n";
      continue;
    }
    if (s[0][0] == 'A' || s[0][m - 1] == 'A' || s[n - 1][0] == 'A' ||
        s[n - 1][m - 1] == 'A') {
      cout << 2 << "\n";
      continue;
    }
    mm = "";
    for (long long i = 0; i < m; i++) mm += "A";
    long long f = 0;
    for (long long i = 0; i < n; i++)
      if (s[i] == mm) {
        cout << 2 << "\n";
        f = 1;
        break;
      }
    if (f == 1) continue;
    mm = "";
    for (long long i = 0; i < n; i++) mm += "A";
    f = 0;
    for (long long j = 0; j < m; j++) {
      string c = "";
      for (long long i = 0; i < n; i++) {
        c += s[i][j];
      }
      if (c == mm) {
        cout << 2 << "\n";
        f = 1;
        break;
      }
      if (f == 1) break;
    }
    if (f == 1) continue;
    if (count((s1).begin(), (s1).end(), 'A') ||
        count((s2).begin(), (s2).end(), 'A') ||
        count((s[0]).begin(), (s[0]).end(), 'A') ||
        count((s[n - 1]).begin(), (s[n - 1]).end(), 'A')) {
      cout << 3 << "\n";
      continue;
    }
    cout << 4 << "\n";
  }
  return 0;
}
