#include <bits/stdc++.h>
#pragma GCC optimize("O3")
using namespace std;
long long gcd(long long a, long long b) {
  long long mi = min(a, b), mx = max(a, b), temp;
  while (mi) {
    temp = mi;
    mi = mx % mi;
    mx = temp;
  }
  return mx;
}
long long pw(long long x, long long n) {
  long long ans = 1;
  while (n) {
    if (n & 1ll) {
      ans *= x;
    }
    x *= x;
    n >>= 1ll;
  }
  return ans;
}
int main() {
  ios ::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long t;
  cin >> t;
  while (t--) {
    long long r, c;
    cin >> r >> c;
    long long v[r][c];
    long long ans = 5, cnt = 0;
    for (long long i = 0; i < r; i++) {
      for (long long j = 0; j < c; j++) {
        char ch;
        cin >> ch;
        if (ch == 'A') {
          v[i][j] = 0;
          ans = 4;
          cnt++;
        } else {
          v[i][j] = 1;
        }
      }
    }
    if (ans == 5) {
      cout << "MORTAL" << '\n';
      continue;
    }
    if (cnt == r * c) {
      cout << 0 << '\n';
      continue;
    }
    for (long long i = 0; i < r; i++) {
      if (v[i][0] == 0 || v[i][c - 1] == 0) {
        ans = 3;
      }
    }
    for (long long j = 0; j < c; j++) {
      if (v[0][j] == 0 || v[r - 1][j] == 0) {
        ans = 3;
      }
    }
    if (ans == 4) {
      cout << ans << '\n';
      continue;
    }
    if (v[0][0] == 0 || v[r - 1][0] == 0 || v[0][c - 1] == 0 ||
        v[r - 1][c - 1] == 0) {
      ans = 2;
    }
    for (long long i = 0; i < r; i++) {
      long long ok = 1;
      for (long long j = 0; j < c; j++) {
        if (v[i][j] == 1) {
          ok = 0;
        }
      }
      if (ok) {
        ans = 2;
      }
    }
    for (long long j = 0; j < c; j++) {
      long long ok = 1;
      for (long long i = 0; i < r; i++) {
        if (v[i][j] == 1) {
          ok = 0;
        }
      }
      if (ok) {
        ans = 2;
      }
    }
    if (ans == 3) {
      cout << ans << '\n';
      continue;
    }
    long long ok;
    ok = 1;
    for (long long i = 0; i < r; i++) {
      if (v[i][0] == 1) {
        ok = 0;
      }
    }
    if (ok) {
      ans = 1;
    }
    ok = 1;
    for (long long i = 0; i < r; i++) {
      if (v[i][c - 1] == 1) {
        ok = 0;
      }
    }
    if (ok) {
      ans = 1;
    }
    ok = 1;
    for (long long j = 0; j < c; j++) {
      if (v[0][j] == 1) {
        ok = 0;
      }
    }
    if (ok) {
      ans = 1;
    }
    ok = 1;
    for (long long j = 0; j < c; j++) {
      if (v[r - 1][j] == 1) {
        ok = 0;
      }
    }
    if (ok) {
      ans = 1;
    }
    cout << ans << '\n';
  }
  return 0;
}
