#include <bits/stdc++.h>
using namespace std;
string s[65];
int main() {
  int nTest;
  cin >> nTest;
  while (nTest--) {
    int r, c;
    cin >> r >> c;
    for (int i = 0; i < r; ++i) cin >> s[i];
    bool all = true;
    bool allP = true;
    for (int i = 0; i < r; ++i) {
      for (int j = 0; j < c; ++j) {
        if (s[i][j] == 'P')
          all = false;
        else
          allP = false;
      }
    }
    if (all) {
      cout << 0 << "\n";
      continue;
    }
    if (allP) {
      cout << "MORTAL\n";
      continue;
    }
    bool row0 = true, rowr = true, col0 = true, colc = true;
    bool haver0 = true, haverr = true, havec0 = true, havecc = true;
    for (int i = 0; i < c; ++i) {
      if (s[0][i] == 'P')
        row0 = false;
      else
        haver0 = false;
      if (s[r - 1][i] == 'P')
        rowr = false;
      else
        haverr = false;
    }
    for (int i = 0; i < r; ++i) {
      if (s[i][0] == 'P')
        col0 = false;
      else
        havec0 = false;
      if (s[i][c - 1] == 'P')
        colc = false;
      else
        havecc = false;
    }
    if (row0 || rowr || col0 || colc) {
      cout << 1 << "\n";
      continue;
    }
    int foo = 0;
    for (int i = 0; i < r; ++i) {
      int bar = 0;
      for (int j = 0; j < c; ++j) {
        if (s[i][j] == 'A') bar++;
      }
      foo = max(foo, bar);
    }
    if (foo == c) {
      cout << 2 << "\n";
      continue;
    }
    foo = 0;
    for (int j = 0; j < c; ++j) {
      int bar = 0;
      for (int i = 0; i < r; ++i) {
        if (s[i][j] == 'A') bar++;
      }
      foo = max(foo, bar);
    }
    if (foo == r) {
      cout << 2 << "\n";
      continue;
    }
    if (s[0][0] == 'A' || s[0][c - 1] == 'A' || s[r - 1][0] == 'A' ||
        s[r - 1][c - 1] == 'A') {
      cout << 2 << "\n";
      continue;
    }
    if (!haver0 || !haverr || !havec0 || !havecc) {
      cout << 3 << "\n";
      continue;
    }
    cout << 4 << "\n";
  }
  return 0;
}
