#include <bits/stdc++.h>
using namespace std;
const int64_t N = 2e5 + 5;
const int64_t INF = 1e18 + 7;
const int64_t MOD = 1e9 + 7;
int64_t n, m;
vector<vector<char>> a;
bool check1() {
  int64_t sum = 0;
  for (int64_t i = 0; i < m; i++)
    if (a[0][i] == 'A') sum++;
  if (sum == m) return true;
  sum = 0;
  for (int64_t i = 0; i < m; i++)
    if (a[n - 1][i] == 'A') sum++;
  if (sum == m) return true;
  sum = 0;
  for (int64_t i = 0; i < n; i++)
    if (a[i][0] == 'A') sum++;
  if (sum == n) return true;
  sum = 0;
  for (int64_t i = 0; i < n; i++)
    if (a[i][m - 1] == 'A') sum++;
  if (sum == n) return true;
  return false;
}
bool check2() {
  if (a[0][0] == 'A' || a[0][m - 1] == 'A' || a[n - 1][0] == 'A' ||
      a[n - 1][m - 1] == 'A')
    return true;
  for (int64_t i = 0; i < n; i++) {
    int64_t sum = 0;
    for (int64_t j = 0; j < m; j++) {
      if (a[i][j] == 'A') sum++;
    }
    if (sum == m) return true;
  }
  for (int64_t i = 0; i < m; i++) {
    int64_t sum = 0;
    for (int64_t j = 0; j < n; j++) {
      if (a[j][i] == 'A') sum++;
    }
    if (sum == n) return true;
  }
  return false;
}
bool check3() {
  for (int64_t i = 0; i < m; i++)
    if (a[0][i] == 'A') return true;
  for (int64_t i = 0; i < m; i++)
    if (a[n - 1][i] == 'A') return true;
  for (int64_t i = 0; i < n; i++)
    if (a[i][0] == 'A') return true;
  for (int64_t i = 0; i < n; i++)
    if (a[i][m - 1] == 'A') return true;
  return false;
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int64_t q;
  cin >> q;
  while (q-- > 0) {
    cin >> n >> m;
    a.clear();
    a.resize(n, vector<char>(m));
    bool good = false;
    bool otlichno = true;
    for (int64_t i = 0; i < n; i++) {
      for (int64_t j = 0; j < m; j++) {
        cin >> a[i][j];
        if (a[i][j] == 'A') good = true;
        if (a[i][j] == 'P') otlichno = false;
      }
    }
    if (otlichno) {
      cout << 0 << endl;
      continue;
    }
    if (!good) {
      cout << "MORTAL" << endl;
      continue;
    }
    if (check1())
      cout << 1 << endl;
    else if (check2())
      cout << 2 << endl;
    else if (check3())
      cout << 3 << endl;
    else
      cout << 4 << endl;
  }
}
