#include <bits/stdc++.h>
using namespace std;
const long long mod = 1e9 + 7, N = 4e5 + 10;
void solve() {
  long long r, c;
  cin >> r >> c;
  char a[r][c];
  long long aw = 0, pu = 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')
        aw++;
      else
        pu++;
    }
  }
  long long c1 = 0, c2 = 0;
  for (long long i = 0; i < r; i++) {
    if (a[i][0] == 'A') c1++;
    if (a[i][c - 1] == 'A') c2++;
  }
  long long r1 = 0, r2 = 0;
  for (long long j = 0; j < c; j++) {
    if (a[0][j] == 'A') r1++;
    if (a[r - 1][j] == 'A') r2++;
  }
  long long flag1 = 0;
  if (a[0][0] == 'A' || a[0][c - 1] == 'A' || a[r - 1][0] == 'A' ||
      a[r - 1][c - 1] == 'A')
    flag1 = 1;
  long long flag2 = 0;
  long long co1 = 0;
  for (long long i = 1; i < r - 1; i++) {
    co1 = 0;
    for (long long j = 0; j < c; j++) {
      if (a[i][j] == 'A') co1++;
    }
    if (co1 == c) {
      flag2 = 1;
      break;
    }
  }
  long long co2 = 0;
  for (long long j = 1; j < c - 1; j++) {
    co2 = 0;
    for (long long i = 0; i < r; i++) {
      if (a[i][j] == 'A') co2++;
    }
    if (co2 == r) {
      flag2 = 1;
      break;
    }
  }
  long long flag3 = 0;
  for (long long i = 1; i < r - 1; i++) {
    if (a[i][0] == 'A') {
      flag3 = 1;
      break;
    }
    if (a[i][c - 1] == 'A') {
      flag3 = 1;
      break;
    }
  }
  for (long long j = 1; j < c - 1; j++) {
    if (a[0][j] == 'A') {
      flag3 = 1;
      break;
    }
    if (a[r - 1][j] == 'A') {
      flag3 = 1;
      break;
    }
  }
  if (aw == 0)
    cout << "MORTAL\n";
  else if (pu == 0)
    cout << "0\n";
  else if (c1 == r || c2 == r || r1 == c || r2 == c) {
    cout << "1\n";
  } else if (flag1 == 1 || flag2 == 1) {
    cout << "2\n";
  } else if (flag3 == 1) {
    cout << "3\n";
  } else
    cout << "4\n";
  return;
}
int32_t main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long test = 1;
  cin >> test;
  while (test--) {
    solve();
  }
}
