#include <bits/stdc++.h>
using namespace std;
mt19937 rnd;
const int N = 70;
int n, m;
bool a[N][N];
bool check_one() {
  bool ok = 1;
  for (int i = 1; i <= n; i++) {
    if (!a[i][1]) {
      ok = 0;
    }
  }
  if (ok) return 1;
  ok = 1;
  for (int i = 1; i <= n; i++) {
    if (!a[i][m]) {
      ok = 0;
    }
  }
  if (ok) return 1;
  ok = 1;
  for (int j = 1; j <= m; j++) {
    if (!a[1][j]) {
      ok = 0;
    }
  }
  if (ok) return 1;
  ok = 1;
  for (int j = 1; j <= m; j++) {
    if (!a[n][j]) {
      ok = 0;
    }
  }
  if (ok) return 1;
  return 0;
}
bool check_two() {
  if (a[1][1] || a[1][m] || a[n][1] || a[n][m]) {
    return 1;
  }
  for (int i = 1; i <= n; i++) {
    bool ok = 1;
    for (int j = 1; j <= m; j++) {
      if (!a[i][j]) {
        ok = 0;
      }
    }
    if (ok) return 1;
  }
  for (int j = 1; j <= m; j++) {
    bool ok = 1;
    for (int i = 1; i <= n; i++) {
      if (!a[i][j]) {
        ok = 0;
      }
    }
    if (ok) return 1;
  }
  return 0;
}
bool check_three() {
  bool ok = 0;
  for (int i = 1; i <= n; i++) {
    if (a[i][1] || a[i][m]) {
      ok = 1;
    }
  }
  for (int j = 1; j <= m; j++) {
    if (a[1][j] || a[n][j]) {
      ok = 1;
    }
  }
  return ok;
}
int solve() {
  bool all_good = 1, all_bad = 1;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      if (a[i][j] == 1) {
        all_bad = 0;
      } else {
        all_good = 0;
      }
    }
  }
  if (all_good) {
    return 0;
  }
  if (all_bad) {
    return -1;
  }
  if (n == 1) {
    if (a[1][1] || a[1][m]) {
      return 1;
    } else {
      return 2;
    }
  }
  if (m == 1) {
    if (a[1][1] || a[n][1]) {
      return 1;
    } else {
      return 2;
    }
  }
  if (check_one()) {
    return 1;
  }
  if (check_two()) {
    return 2;
  }
  if (check_three()) {
    return 3;
  }
  return 4;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  int t;
  cin >> t;
  while (t--) {
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
      for (int j = 1; j <= m; j++) {
        char c;
        cin >> c;
        if (c == 'A') {
          a[i][j] = 1;
        } else {
          a[i][j] = 0;
        }
      }
    }
    int ans = solve();
    if (ans == -1) {
      cout << "MORTAL\n";
    } else {
      cout << ans << "\n";
    }
  }
  return 0;
}
