#include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
char maxCol(vector<string>& vs, int c) {
  int n = vs.size(), m = vs[0].size();
  char ans = vs[0][c];
  for (int i = 0; i < n; i++) {
    ans = max(ans, vs[i][c]);
  }
  return ans;
}
char maxRow(vector<string>& vs, int r) {
  return *max_element(vs[r].begin(), vs[r].end());
}
char minCol(vector<string>& vs, int c) {
  int n = vs.size(), m = vs[0].size();
  char ans = vs[0][c];
  for (int i = 0; i < n; i++) {
    ans = min(ans, vs[i][c]);
  }
  return ans;
}
char minRow(vector<string>& vs, int r) {
  return *min_element(vs[r].begin(), vs[r].end());
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  int t;
  cin >> t;
  while (t--) {
    int n, m;
    cin >> n >> m;
    vector<string> vs(n);
    for (auto& s : vs) cin >> s;
    bool f = 0;
    for (int i = 0; i < n && !f; i++) {
      if (minRow(vs, i) == 'A') f = 1;
    }
    if (!f) {
      cout << "MORTAL\n";
      continue;
    }
    f = 0;
    for (int i = 0; i < n && !f; i++) {
      if (maxRow(vs, i) == 'P') f = 1;
    }
    if (!f) {
      cout << "0\n";
      continue;
    }
    if (maxCol(vs, 0) == 'A' || maxCol(vs, m - 1) == 'A' ||
        maxRow(vs, 0) == 'A' || maxRow(vs, n - 1) == 'A') {
      cout << "1\n";
      continue;
    }
    if (vs[0][0] == 'A' || vs[0][m - 1] == 'A' || vs[n - 1][0] == 'A' ||
        vs[n - 1][m - 1] == 'A') {
      cout << "2\n";
      continue;
    }
    f = 0;
    for (int i = 0; i < n && !f; i++) {
      if (maxRow(vs, i) == 'A') f = 1;
    }
    if (f) {
      cout << "2\n";
      continue;
    }
    for (int j = 0; j < m && !f; j++) {
      if (maxCol(vs, j) == 'A') f = 1;
    }
    if (f) {
      cout << "2\n";
      continue;
    }
    if (minCol(vs, 0) == 'A' || minCol(vs, m - 1) == 'A' ||
        minRow(vs, 0) == 'A' || minRow(vs, n - 1) == 'A') {
      cout << "3\n";
      continue;
    }
    cout << "4\n";
  }
  return 0;
}
