#include <bits/stdc++.h>
using namespace std;
const int MAXN = 3e6 + 5;
const int MOD = 1e9 + 7;
char A[66][66];
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int T;
  cin >> T;
  while (T--) {
    int n, m, ans = 4;
    cin >> n >> m;
    bool hp = 0, ha = 0;
    for (int i = 1; i <= n; i++) {
      cin >> A[i] + 1;
      for (int j = 1; j <= m; j++) {
        if (A[i][j] == 'P') hp = 1;
        if (A[i][j] == 'A') ha = 1;
      }
    }
    if (!hp) ans = 0;
    if (!ha) {
      cout << "MORTAL\n";
      continue;
    }
    bool a, b, c, d, e;
    a = b = c = d = 1;
    e = 0;
    for (int i = 1; i <= n; i++) {
      if (A[i][1] == 'P')
        a = 0;
      else
        e = 1;
      if (A[i][m] == 'P')
        b = 0;
      else
        e = 1;
    }
    for (int i = 1; i <= m; i++) {
      if (A[1][i] == 'P')
        c = 0;
      else
        e = 1;
      if (A[n][i] == 'P')
        d = 0;
      else
        e = 1;
    }
    if (a || b || c || d) ans = min(ans, 1);
    if (A[1][1] == 'A' || A[1][m] == 'A' || A[n][1] == 'A' || A[n][m] == 'A')
      ans = min(ans, 2);
    for (int i = 1; i <= n; i++) {
      bool pos = 1;
      for (int j = 1; j <= m; j++)
        if (A[i][j] == 'P') pos = 0;
      if (pos) ans = min(ans, 2);
    }
    for (int i = 1; i <= m; i++) {
      bool pos = 1;
      for (int j = 1; j <= n; j++)
        if (A[j][i] == 'P') pos = 0;
      if (pos) ans = min(ans, 2);
    }
    if (e) ans = min(ans, 3);
    cout << ans << '\n';
  }
}
