#include <bits/stdc++.h>
using namespace std;
const int N = 70;
string m[N];
int main() {
  int t;
  cin >> t;
  while (t--) {
    int r, c;
    cin >> r >> c;
    for (int i = 0; i < r; i++) {
      cin >> m[i];
    }
    bool f1[c];
    bool f2[r];
    bool gc[c];
    bool gr[r];
    for (int i = 0; i < r; i++) f2[i] = 1, gr[i] = 1;
    for (int j = 0; j < c; j++) f1[j] = 1, gc[j] = 1;
    bool aha = 0;
    bool bha = 0;
    for (int i = 0; i < r; i++)
      for (int j = 0; j < c; j++) {
        if (m[i][j] == 'P')
          f2[i] = 0, f1[j] = 0, bha = 1;
        else
          gr[i] = 0, gc[j] = 0, aha = 1;
      }
    if (!bha) {
      cout << 0 << endl;
      continue;
    }
    if (f1[0] || f1[c - 1] || f2[0] || f2[r - 1]) {
      cout << 1 << endl;
      continue;
    }
    bool flag = 0;
    bool glag = 0;
    for (int i = 0; i < r; i++) flag = flag || f2[i];
    for (int j = 0; j < c; j++) flag = flag || f1[j];
    if (flag || m[0][0] == 'A' || m[0][c - 1] == 'A' || m[r - 1][0] == 'A' ||
        m[r - 1][c - 1] == 'A') {
      cout << 2 << endl;
      continue;
    }
    if (!(gr[0] && gr[r - 1] && gc[0] && gc[c - 1])) {
      cout << 3 << endl;
      continue;
    }
    if (aha) {
      cout << 4 << endl;
    } else {
      cout << "MORTAL" << endl;
    }
  }
}
