#include <bits/stdc++.h>
using namespace std;
void printvector(std::vector<long long> v) {
  for (long long i = 0; i < v.size(); ++i) {
    cout << v[i] << " ";
  }
  cout << "" << endl;
}
void printarray(long long a[], long long n) {
  for (long long i = 0; i < n; ++i) {
    cout << a[i] << " ";
  }
  cout << "" << endl;
}
void solve() {
  long long n, m;
  cin >> n >> m;
  char A[n][m];
  bool ap1 = false;
  bool ap2 = false;
  for (long long i = 0; i < n; i++) {
    for (long long j = 0; j < m; j++) {
      cin >> A[i][j];
      if (A[i][j] == 'A') ap1 = true;
      if (A[i][j] == 'P') ap2 = true;
    }
  }
  if (!ap1) {
    cout << "MORTAL" << endl;
    return;
  }
  if (!ap2) {
    cout << 0 << endl;
    return;
  }
  bool ap = true;
  for (long long i = 0; i < m; i++) {
    if (A[0][i] == 'P') ap = false;
  }
  if (ap) {
    cout << 1 << endl;
    return;
  }
  ap = true;
  for (long long i = 0; i < m; i++) {
    if (A[n - 1][i] == 'P') ap = false;
  }
  if (ap) {
    cout << 1 << endl;
    return;
  }
  ap = true;
  for (long long i = 0; i < n; i++) {
    if (A[i][0] == 'P') ap = false;
  }
  if (ap) {
    cout << 1 << endl;
    return;
  }
  ap = true;
  for (long long i = 0; i < n; i++) {
    if (A[i][m - 1] == 'P') ap = false;
  }
  if (ap) {
    cout << 1 << endl;
    return;
  }
  for (long long i = 1; i < n - 1; i++) {
    ap = true;
    for (long long j = 0; j < m; j++) {
      if (A[i][j] == 'P') ap = false;
    }
    if (ap) {
      cout << 2 << endl;
      return;
    }
  }
  for (long long i = 1; i < m - 1; i++) {
    ap = true;
    for (long long j = 0; j < n; j++) {
      if (A[j][i] == 'P') ap = false;
    }
    if (ap) {
      cout << 2 << endl;
      return;
    }
  }
  if (A[0][0] == 'A' || A[0][m - 1] == 'A' || A[n - 1][0] == 'A' ||
      A[n - 1][m - 1] == 'A') {
    cout << 2 << endl;
    return;
  }
  ap = true;
  for (long long i = 0; i < n; i++) {
    for (long long j = 0; j < m; ++j) {
      if (i == 0 || i == n - 1 || j == 0 || j == m - 1) {
        if (A[i][j] == 'A') ap = false;
      }
    }
  }
  if (ap) {
    cout << 4 << endl;
    return;
  }
  cout << 3 << endl;
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long t;
  cin >> t;
  while (t--) solve();
  return 0;
}
