#include <bits/stdc++.h>
using namespace std;
long long power(long long x, long long y, long long m) {
  if (y == 0) return 1;
  long long p = power(x, y / 2, m) % m;
  p = (p * p) % m;
  return (y % 2 == 0) ? p : (x * p) % m;
}
long long gcd(long long a, long long b) {
  if (a > b) swap(a, b);
  if (a == 0) return b;
  return gcd(b % a, a);
}
long long modInverse(long long a, long long m) { return power(a, m - 2, m); }
int main() {
  ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
  srand(time(NULL));
  ;
  long long t;
  cin >> t;
  while (t--) {
    long long r, c, f = 0, f1 = 0, f2 = 0;
    cin >> r >> c;
    char a[r][c];
    long long c1 = 0, c2 = 0;
    for (long long i = 0; i < r; i++) {
      for (long long j = 0; j < c; j++) {
        cin >> a[i][j];
        if (a[i][j] == 'A')
          c1++;
        else
          c2++;
      }
    }
    if (c1 == 0)
      cout << "MORTAL" << endl;
    else if (c2 == 0)
      cout << "0" << endl;
    else {
      f = 0;
      for (long long i = 0; i < c; i++)
        if (a[0][i] == 'A') f++;
      if (f == c) {
        cout << "1" << endl;
        continue;
      }
      f2 += f;
      f = 0;
      for (long long i = 0; i < c; i++)
        if (a[r - 1][i] == 'A') f++;
      if (f == c) {
        cout << "1" << endl;
        continue;
      }
      f2 += f;
      f = 0;
      for (long long i = 0; i < r; i++)
        if (a[i][0] == 'A') f++;
      if (f == r) {
        cout << "1" << endl;
        continue;
      }
      f2 += f;
      f = 0;
      for (long long i = 0; i < r; i++)
        if (a[i][c - 1] == 'A') f++;
      if (f == r) {
        cout << "1" << endl;
        continue;
      }
      f2 += f;
      f = 0;
      if (f2 == 0) {
        cout << "4" << endl;
        continue;
      }
      if (a[0][0] == 'A' || a[r - 1][0] == 'A' || a[0][c - 1] == 'A' ||
          a[r - 1][c - 1] == 'A') {
        cout << "2" << endl;
        continue;
      }
      for (long long i = 1; i < r - 1; i++) {
        f = 0;
        for (long long j = 0; j < c; j++) {
          if (a[i][j] == 'A') f++;
        }
        if (f == c) break;
      }
      if (f == c) {
        cout << "2" << endl;
        continue;
      }
      for (long long i = 1; i < c - 1; i++) {
        f = 0;
        for (long long j = 0; j < r; j++) {
          if (a[j][i] == 'A') f++;
        }
        if (f == r) break;
      }
      if (f == r) {
        cout << "2" << endl;
        continue;
      }
      cout << "3" << endl;
    }
  }
}
