#include <bits/stdc++.h>
using namespace std;
mt19937 rd(chrono::steady_clock::now().time_since_epoch().count());
const long long mod = 1e9 + 7;
const long long inf = 1e9;
long long add(long long x, long long y) { return (1ll * x + 1ll * y) % mod; }
long long del(long long x, long long y) {
  return ((1ll * x - 1ll * y) % mod + mod) % mod;
}
long long mul(long long x, long long y) { return (1ll * x * 1ll * y) % mod; }
const long long N = 3e5 + 5;
long long test, r, c, a[65][65];
signed main() {
  cin.tie(0), ios_base::sync_with_stdio(0);
  cin >> test;
  while (test--) {
    cin >> r >> c;
    long long cnt = 0;
    for (long long i = 1; i <= r; i++) {
      for (long long j = 1; j <= c; j++) {
        char h;
        cin >> h;
        if (h == 'A')
          a[i][j] = 0;
        else
          a[i][j] = 1;
        cnt += a[i][j];
      }
    }
    if (!cnt) {
      cout << "0\n";
      continue;
    }
    if (cnt == r * c) {
      cout << "MORTAL\n";
      continue;
    }
    long long sum1 = 0, sum2 = 0, sum3 = 0, sum4 = 0;
    for (long long i = 1; i <= r; i++) sum1 += a[i][1], sum2 += a[i][c];
    if (sum1 == 0 || sum2 == 0) {
      cout << "1\n";
      continue;
    }
    for (long long i = 1; i <= c; i++) sum3 += a[1][i], sum4 += a[r][i];
    if (sum3 == 0 || sum4 == 0) {
      cout << "1\n";
      continue;
    }
    if (!a[1][1] || !a[r][1] || !a[1][c] || !a[r][c]) {
      cout << "2\n";
      continue;
    }
    bool ok = 0;
    for (long long i = 1; i <= r; i++) {
      long long sum = 0;
      for (long long j = 1; j <= c; j++) {
        sum += a[i][j];
      }
      if (!sum) ok = 1;
    }
    for (long long j = 1; j <= c; j++) {
      long long sum = 0;
      for (long long i = 1; i <= r; i++) {
        sum += a[i][j];
      }
      if (!sum) ok = 1;
    }
    if (ok) {
      cout << "2\n";
      continue;
    }
    if (sum1 != r || sum2 != r || sum3 != c || sum4 != c) {
      cout << "3\n";
      continue;
    }
    cout << "4\n";
  }
}
