#include <bits/stdc++.h>
#pragma comment(linker, "/STACK:10000000000")
using namespace std;
const int INF = 1000000007;
const long long INF2 = 1000000000000000007;
const long long MOD = 998244353;
const long long MOD1 = 1864463441;
const int SIZE = 300010;
const double eps = 1e-6;
uniform_int_distribution<int> uid(5, 10);
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int t, n, m, cntx, cnty, bufx, bufy;
char ar[100][100];
bool fl, fl1, fl2, fl3, fl4, wa8;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cin >> t;
  while (t--) {
    cin >> n >> m;
    fl = 0;
    fl1 = 0;
    fl2 = 0;
    fl3 = 0;
    fl4 = 0;
    bufx = 0;
    bufy = 0;
    wa8 = 0;
    for (int i = 0; i < n; ++i) {
      cntx = 0;
      for (int j = 0; j < m; ++j) {
        cin >> ar[i][j];
        if (ar[i][j] == 'A' && (i == 0 || i == n - 1 || j == 0 || j == m - 1))
          fl = 1;
        if (ar[i][j] == 'A') cntx++;
        if (ar[i][j] == 'P') wa8 = 1;
      }
      if (cntx > 0) fl3 = 1;
      if (cntx == m) {
        bufx = i;
        if (bufx == 0 || bufx == n - 1) fl1 = 1;
      }
    }
    for (int i = 0; i < m; ++i) {
      cnty = 0;
      for (int j = 0; j < n; ++j) {
        if (ar[j][i] == 'A') cnty++;
      }
      if (cnty > 0) fl3 = 1;
      if (cnty == n) {
        bufy = i;
        if (bufy == 0 || bufy == m - 1) fl1 = 1;
      }
    }
    if (ar[0][0] == 'A' || ar[0][m - 1] == 'A' || ar[n - 1][0] == 'A' ||
        ar[n - 1][m - 1] == 'A')
      fl4 = 1;
    if (!wa8)
      cout << 0 << endl;
    else if (fl1)
      cout << 1 << endl;
    else if (fl4 || bufx || bufy)
      cout << 2 << endl;
    else if (fl)
      cout << 3 << endl;
    else if (fl3)
      cout << 4 << endl;
    else
      cout << "MORTAL\n";
  }
  return 0;
}
