#include <bits/stdc++.h>
using namespace std;
const int inf = 2e9;
const long long INF = 8e18;
const int maxn = 105;
int r, c, cnt;
char a[maxn][maxn];
inline bool check1() {
  cnt = 0;
  for (int i = 1; i <= r; ++i)
    if (a[i][1] == 'A') ++cnt;
  if (cnt == r) return 1;
  cnt = 0;
  for (int i = 1; i <= r; ++i)
    if (a[i][c] == 'A') ++cnt;
  if (cnt == r) return 1;
  cnt = 0;
  for (int j = 1; j <= c; ++j)
    if (a[1][j] == 'A') ++cnt;
  if (cnt == c) return 1;
  cnt = 0;
  for (int j = 1; j <= c; ++j)
    if (a[r][j] == 'A') ++cnt;
  if (cnt == c) return 1;
  return 0;
}
inline bool check2() {
  if (a[1][1] == 'A' || a[r][1] == 'A' || a[1][c] == 'A' || a[r][c] == 'A')
    return 1;
  for (int i = 1; i <= r; ++i) {
    cnt = 0;
    for (int j = 1; j <= c; ++j)
      if (a[i][j] == 'A') ++cnt;
    if (cnt == c) return 1;
  }
  for (int j = 1; j <= c; ++j) {
    cnt = 0;
    for (int i = 1; i <= r; ++i)
      if (a[i][j] == 'A') ++cnt;
    if (cnt == r) return 1;
  }
  return 0;
}
inline bool check3() {
  for (int i = 1; i <= r; ++i) {
    if (a[i][1] == 'A') return 1;
    if (a[i][c] == 'A') return 1;
  }
  for (int j = 1; j <= c; ++j) {
    if (a[1][j] == 'A') return 1;
    if (a[r][j] == 'A') return 1;
  }
  return 0;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int t;
  cin >> t;
  while (t--) {
    cin >> r >> c;
    cnt = 0;
    for (int i = 1; i <= r; ++i)
      for (int j = 1; j <= c; ++j) {
        cin >> a[i][j];
        if (a[i][j] == 'A') ++cnt;
      }
    if (cnt == r * c) {
      cout << 0 << '\n';
      continue;
    }
    if (!cnt) {
      cout << "MORTAL" << '\n';
      continue;
    }
    if (check1()) {
      cout << 1 << '\n';
      continue;
    }
    if (check2()) {
      cout << 2 << '\n';
      continue;
    }
    if (check3()) {
      cout << 3 << '\n';
      continue;
    }
    cout << 4 << '\n';
  }
  return 0;
}
