#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  cin >> t;
  while (t--) {
    int ret = -1;
    int r, c;
    cin >> r >> c;
    vector<string> g(r);
    for (int i = 0; i < r; i++) {
      cin >> g[i];
      for (int j = 0; j < c; j++) {
        if (g[i][j] == 'A') ret = 4;
      }
    }
    if (ret < 0) {
      cout << "MORTAL" << endl;
      continue;
    }
    int good = 0;
    vector<int> R(r, 0), C(c, 0);
    for (int i = 0; i < r; i++) {
      for (int j = 0; j < c; j++) {
        if (g[i][j] == 'P') continue;
        bool a = (i == 0 || i == r - 1);
        bool b = (j == 0 || j == c - 1);
        if (++R[i] == c) ret = min(ret, a ? 1 : 2);
        if (++C[j] == r) ret = min(ret, b ? 1 : 2);
        good++;
        if (a && b) ret = min(ret, 2);
        if (a || b) ret = min(ret, 3);
      }
    }
    if (good == r * c) ret = 0;
    cout << ret << endl;
  }
  return 0;
}
