#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1000 * 1000 * 1000 + 7;
const long long INF = 1ll * 1000 * 1000 * 1000 * 1000 * 1000 * 1000 + 7;
const long long MOD2 = 998244353;
const long long N = 5000 + 10;
const long long N2 = 1000 * 1000;
const long double PI = 3.14159265;
long long gcd(long long a, long long b) {
  if (!b) return a;
  return gcd(b, a % b);
}
long long power(long long x, long long y, long long p = INF) {
  long long res = 1;
  x %= p;
  while (y > 0) {
    if (y & 1) res = (res * x) % p;
    y = y >> 1;
    x = (x * x) % p;
  }
  return res;
}
signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int t;
  cin >> t;
  while (t--) {
    int r, c;
    cin >> r >> c;
    int total = r * c;
    int ans = 4;
    int count = 0;
    char a[r][c];
    for (int i = 0; i < r; ++i) {
      for (int j = 0; j < c; ++j) {
        cin >> a[i][j];
        if (a[i][j] == 'A') count++;
      }
    }
    if (!count) {
      cout << "MORTAL"
           << "\n";
      continue;
    }
    if (count == total) {
      cout << 0 << "\n";
      continue;
    }
    count = 0;
    for (int i = 0; i < r; ++i) {
      if (a[i][0] == 'A') count++;
    }
    if (count == r) ans = min(ans, 1);
    if (count) ans = min(ans, 3);
    count = 0;
    for (int i = 0; i < r; ++i) {
      if (a[i][c - 1] == 'A') count++;
    }
    if (count == r) ans = min(ans, 1);
    if (count) ans = min(ans, 3);
    count = 0;
    for (int i = 0; i < c; ++i) {
      if (a[r - 1][i] == 'A') count++;
    }
    if (count == c) ans = min(ans, 1);
    if (count) ans = min(ans, 3);
    count = 0;
    for (int i = 0; i < c; ++i) {
      if (a[0][i] == 'A') count++;
    }
    if (count == c) ans = min(ans, 1);
    if (count) ans = min(ans, 3);
    if (a[0][0] == 'A' || a[r - 1][c - 1] == 'A' || a[r - 1][0] == 'A' ||
        a[0][c - 1] == 'A')
      ans = min(ans, 2);
    for (int i = 1; i < r - 1; i++) {
      count = 0;
      for (int j = 0; j < c; ++j) {
        if (a[i][j] == 'A') {
          count++;
        }
      }
      if (count == c) {
        ans = min(ans, 2);
      }
    }
    for (int i = 1; i < c - 1; i++) {
      count = 0;
      for (int j = 0; j < r; ++j) {
        if (a[j][i] == 'A') {
          count++;
        }
      }
      if (count == r) {
        ans = min(ans, 2);
      }
    }
    cout << ans << "\n";
  }
  return 0;
}
