#include <bits/stdc++.h>
using namespace std;
int t;
int main() {
  ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
  cin >> t;
  while (t--) {
    int n, m;
    cin >> n >> m;
    char a[n + 17][m + 17];
    bool flag = false, flag2 = false;
    for (int i = 1; i <= n; i++)
      for (int j = 1; j <= m; j++)
        cin >> a[i][j], flag |= (a[i][j] == 'A'), flag2 |= (a[i][j] == 'P');
    if (!flag) {
      cout << "MORTAL" << endl;
      continue;
    }
    if (!flag2) {
      cout << 0 << endl;
      continue;
    }
    bool c1 = false, cm = false, r1 = false, rn = false;
    bool ist = false;
    for (int i = 1; i <= n; i++) {
      if (a[i][1] == 'P') c1 = true;
      if (a[i][m] == 'P') cm = true;
      if (a[i][1] == 'A' || a[i][m] == 'A') ist = true;
    }
    for (int j = 1; j <= m; j++) {
      if (a[1][j] == 'P') r1 = true;
      if (a[n][j] == 'P') rn = true;
      if (a[1][j] == 'A' || a[n][j] == 'A') ist = true;
    }
    if (!c1 || !cm || !r1 || !rn) {
      cout << 1 << endl;
      continue;
    }
    if (a[1][1] == 'A' || a[1][m] == 'A' || a[n][1] == 'A' || a[n][m] == 'A') {
      cout << 2 << endl;
      continue;
    }
    bool is2 = false;
    for (int i = 1; i <= n; i++) {
      bool ok = false;
      for (int j = 1; j <= m; j++)
        if (a[i][j] == 'P') ok = true;
      if (!ok) is2 = true;
    }
    for (int j = 1; j <= m; j++) {
      bool ok = false;
      for (int i = 1; i <= n; i++)
        if (a[i][j] == 'P') ok = true;
      if (!ok) is2 = true;
    }
    if (is2) {
      cout << 2 << endl;
      continue;
    }
    if (ist) {
      cout << 3 << endl;
      continue;
    }
    cout << 4 << endl;
  }
  return 0;
}
