#include <bits/stdc++.h>
using namespace std;
const long long mod = 1e9 + 7;
string arr[105];
bool row[105];
bool col[105];
void solve() {
  int n, m;
  cin >> n >> m;
  for (int i = 0; i < n; i++) cin >> arr[i];
  for (int i = 0; i < n; i++) row[i] = false;
  for (int i = 0; i < m; i++) col[i] = false;
  for (int i = 0; i < n; i++) {
    bool all = true;
    for (int j = 0; j < m; j++) {
      if (arr[i][j] == 'P') all = false;
    }
    if (all) row[i] = true;
  }
  for (int i = 0; i < m; i++) {
    bool all = true;
    for (int j = 0; j < n; j++) {
      if (arr[j][i] == 'P') all = false;
    }
    if (all) col[i] = true;
  }
  int a = 0;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) a += (arr[i][j] == 'A');
  }
  if (!a)
    cout << "MORTAL" << '\n';
  else if (a == n * m)
    cout << 0 << '\n';
  else {
    bool exist = false;
    for (int i = 0; i < m; i++)
      if (arr[0][i] == 'A') exist = true;
    for (int i = 0; i < n; i++)
      if (arr[i][0] == 'A') exist = true;
    for (int i = 0; i < m; i++)
      if (arr[n - 1][i] == 'A') exist = true;
    for (int i = 0; i < n; i++)
      if (arr[i][m - 1] == 'A') exist = true;
    if (!exist)
      cout << 4 << '\n';
    else {
      if (row[0] || row[n - 1] || col[0] || col[m - 1])
        cout << 1 << '\n';
      else {
        if (arr[0][0] == 'A' || arr[0][m - 1] == 'A' || arr[n - 1][0] == 'A' ||
            arr[n - 1][m - 1] == 'A')
          cout << 2 << '\n';
        else {
          for (int i = 0; i < n; i++)
            if (row[i]) {
              cout << 2 << '\n';
              return;
            }
          for (int i = 0; i < m; i++)
            if (col[i]) {
              cout << 2 << '\n';
              return;
            }
          cout << 3 << '\n';
        }
      }
    }
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int t = 1;
  cin >> t;
  while (t--) solve();
}
