#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1000000007;
long long exp(long long a, long long e) {
  long long ans = 1;
  while (e > 0) {
    if (e % 2 != 0) {
      ans = (ans * a) % MOD;
    }
    e /= 2;
    a = (a * a) % MOD;
  }
  return ans;
}
void Swap(long long &a, long long &b) {
  long long temp;
  temp = a;
  a = b;
  b = temp;
}
bool checkAnyEdgeHasPrefSuffA(vector<string> &Matrix, long long r,
                              long long c) {
  if (Matrix[0][0] == 'A' || Matrix[r - 1][0] == 'A' ||
      Matrix[0][c - 1] == 'A' || Matrix[r - 1][c - 1] == 'A')
    return true;
  return false;
}
bool checkAnyRowA(vector<string> &Matrix, long long r, long long c) {
  for (long long i = 0; i < r; i++) {
    bool flag = true;
    for (long long j = 0; j < c; j++) {
      if (Matrix[i][j] == 'P') {
        flag = false;
        break;
      }
    }
    if (flag) return true;
  }
  return false;
}
bool checkAnyColA(vector<string> &Matrix, long long r, long long c) {
  for (long long j = 0; j < c; j++) {
    bool flag = true;
    for (long long i = 0; i < r; i++) {
      if (Matrix[i][j] == 'P') {
        flag = false;
        break;
      }
    }
    if (flag) return true;
  }
  return false;
}
bool checkAnyEdgeHasA(vector<string> &Matrix, long long r, long long c) {
  for (long long i = 0; i < c; i++) {
    if (Matrix[0][i] == 'A' || Matrix[r - 1][i] == 'A') return true;
  }
  for (long long i = 0; i < r; i++) {
    if (Matrix[i][0] == 'A' || Matrix[i][c - 1] == 'A') return true;
  }
  return false;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long t, r, c, i, j;
  cin >> t;
  while (t--) {
    cin >> r >> c;
    vector<string> Matrix(r);
    long long ctrA = 0;
    long long ctrP = 0;
    long long P_l, P_r, P_t, P_b;
    P_l = c + 1;
    P_b = -1;
    P_r = -1;
    P_t = r + 1;
    for (i = 0; i < r; i++) {
      cin >> Matrix[i];
      for (j = 0; j < c; j++) {
        if (Matrix[i][j] == 'A') {
          ctrA++;
        } else {
          P_l = min(P_l, j);
          P_b = max(P_b, i);
          P_t = min(P_t, i);
          P_r = max(P_r, j);
          ctrP++;
        }
      }
    }
    if (ctrA == r * c) {
      cout << "0\n";
      goto END;
    }
    if (ctrP == r * c) {
      cout << "MORTAL\n";
      goto END;
    }
    if (P_l > 0 || P_r < c - 1 || P_b < r - 1 || P_t > 0) {
      cout << "1\n";
      goto END;
    }
    if (checkAnyEdgeHasPrefSuffA(Matrix, r, c) || checkAnyRowA(Matrix, r, c) ||
        checkAnyColA(Matrix, r, c)) {
      cout << "2\n";
      goto END;
    }
    if (checkAnyEdgeHasA(Matrix, r, c)) {
      cout << "3\n";
      goto END;
    }
    cout << "4\n";
  END:;
  }
  return 0;
}
