#include <bits/stdc++.h>
const long long maxn = 1e5 * 5 + 5, base = 31, mod = 1e9 + 9;
using namespace std;
int main() {
  ios::sync_with_stdio(false), cin.tie(0);
  int t;
  cin >> t;
  int N, M, mat[61][61], HOR[61], VER[61];
  while (t--) {
    memset(mat, 0, sizeof(mat));
    memset(HOR, 0, sizeof(HOR));
    memset(VER, 0, sizeof(VER));
    cin >> N >> M;
    int ff = 0;
    for (int i = 0; i < N; i++) {
      for (int j = 0; j < M; j++) {
        char aux;
        cin >> aux;
        if (aux == 'A') {
          mat[i][j] = 1;
          ff++;
        }
      }
    }
    if (!ff) {
      cout << "MORTAL\n";
      continue;
    }
    if (ff == N * M) {
      cout << "0\n";
      continue;
    }
    int ans = 4;
    for (int i = 0; i < N; i++) {
      if (mat[i][0] || mat[i][M - 1]) ans = 3;
    }
    for (int j = 0; j < M; j++) {
      if (mat[0][j] || mat[N - 1][j]) ans = 3;
    }
    if (mat[0][0] || mat[N - 1][0] || mat[0][M - 1] || mat[N - 1][M - 1]) {
      ans = 2;
    }
    int hor = 0, ver = 0;
    for (int i = 0; i < N; i++) {
      for (int j = 0; j < M; j++) {
        if (!mat[i][j]) continue;
        int H = 1;
        for (int k = j + 1; k < M; k++) {
          if (mat[i][k])
            H++;
          else
            break;
        }
        for (int k = j - 1; k > 0; k--) {
          if (mat[i][k])
            H++;
          else
            break;
        }
        int V = 1;
        for (int k = i + 1; k < N; k++) {
          if (mat[k][j])
            V++;
          else
            break;
        }
        for (int k = i - 1; k > 0; k--) {
          if (mat[k][j])
            V++;
          else
            break;
        }
        HOR[i] = max(HOR[i], H);
        VER[j] = max(VER[j], V);
        hor = max(hor, H);
        ver = max(ver, V);
      }
    }
    if (hor == M || ver == N) {
      ans = 2;
    }
    if (HOR[0] == M || HOR[N - 1] == M || VER[0] == N || VER[M - 1] == N) {
      ans = 1;
    }
    cout << ans << "\n";
  }
  return 0;
}
