#include <bits/stdc++.h>
using namespace std;
std::mt19937 rng(
    (int)std::chrono::steady_clock::now().time_since_epoch().count());
const double EPS = 1e-9;
const double PI = acos(-1);
const int MOD = 1000000007;
char mat[100][100];
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int t;
  cin >> t;
  while (t--) {
    int n, m;
    cin >> n >> m;
    bool case0 = true;
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        cin >> mat[i][j];
        if (mat[i][j] == 'P') case0 = false;
      }
    }
    if (case0) {
      cout << 0 << '\n';
      continue;
    }
    bool a1 = true, a2 = true, a3 = true, a4 = true;
    for (int i = 0; i < n; i++) {
      a1 = a1 & (mat[i][0] == 'A');
      a2 = a2 & (mat[i][m - 1] == 'A');
    }
    for (int i = 0; i < m; i++) {
      a3 = a3 & (mat[0][i] == 'A');
      a4 = a4 & (mat[n - 1][i] == 'A');
    }
    if (a1 or a2 or a3 or a4) {
      cout << 1 << '\n';
      continue;
    }
    bool case2 = (mat[0][0] == 'A') || (mat[0][m - 1] == 'A') ||
                 (mat[n - 1][0] == 'A') || (mat[n - 1][m - 1] == 'A');
    for (int i = 0; i < n; i++) {
      bool linha = true;
      for (int j = 0; j < m; j++) {
        linha = linha & (mat[i][j] == 'A');
      }
      case2 = case2 | linha;
    }
    for (int j = 0; j < m; j++) {
      bool col = true;
      for (int i = 0; i < n; i++) {
        col = col & (mat[i][j] == 'A');
      }
      case2 = case2 | col;
    }
    if (case2) {
      cout << 2 << '\n';
      continue;
    }
    bool case3 = false;
    for (int i = 0; i < n; i++) {
      case3 = case3 | (mat[i][0] == 'A');
      case3 = case3 | (mat[i][m - 1] == 'A');
    }
    for (int i = 0; i < m; i++) {
      case3 = case3 | (mat[0][i] == 'A');
      case3 = case3 | (mat[n - 1][i] == 'A');
    }
    if (case3) {
      cout << 3 << '\n';
      continue;
    }
    bool case4 = false;
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        case4 = case4 | (mat[i][j] == 'A');
      }
    }
    if (case4)
      cout << 4 << '\n';
    else
      cout << "MORTAL" << '\n';
  }
  return 0;
}
