#include <bits/stdc++.h>
using namespace std;
string grid[60];
int main() {
  cin.tie(0);
  ios::sync_with_stdio(0);
  int t;
  cin >> t;
  int r, c;
  while (t--) {
    cin >> r >> c;
    for (int i = 0; i < r; i++) cin >> grid[i];
    bool quina = false, borda = false, meio = false, all = true, tdb1 = true,
         tdb2 = true, tdb3 = true, tdb4 = true, tdm1 = false, tdm2 = false;
    for (int i = 0; i < r; i++) {
      bool at = true;
      for (int j = 0; j < c; j++) {
        if (grid[i][j] == 'A') {
          if ((i == 0 && j == 0) || (i == 0 && j == c - 1) ||
              (i == r - 1 && j == 0) || (i == r - 1 && j == c - 1))
            quina = true;
          else if (i == 0 || j == c - 1 || i == r - 1 || j == 0)
            borda = true;
          else
            meio = true;
        } else {
          all = false;
          at = false;
        }
      }
      tdm1 = tdm1 || at;
    }
    for (int i = 0; i < c; i++) {
      bool at = true;
      for (int j = 0; j < r; j++) {
        if (grid[j][i] == 'P') {
          at = false;
        }
      }
      tdm2 = tdm2 || at;
    }
    for (int i = 0; i < r; i++) {
      if (grid[i][0] == 'P') tdb1 = false;
    }
    for (int i = 0; i < r; i++) {
      if (grid[i][c - 1] == 'P') tdb2 = false;
    }
    for (int i = 0; i < c; i++) {
      if (grid[0][i] == 'P') tdb3 = false;
    }
    for (int i = 0; i < c; i++) {
      if (grid[r - 1][i] == 'P') tdb4 = false;
    }
    if (all)
      cout << 0 << endl;
    else if (tdb1 || tdb2 || tdb3 || tdb4)
      cout << 1 << endl;
    else if (quina || tdm1 || tdm2)
      cout << 2 << endl;
    else if (borda)
      cout << 3 << endl;
    else if (meio)
      cout << 4 << endl;
    else
      cout << "MORTAL" << endl;
  }
}
