#include <bits/stdc++.h>
using namespace std;
bool A[70][70];
int n, t, r, c;
bool can() {
  for (int i = 0; i < r; ++i) {
    int cnt = 0;
    for (int j = 0; j < c; ++j) cnt += A[i][j];
    if (cnt == c) return 1;
  }
  for (int i = 0; i < c; ++i) {
    int cnt = 0;
    for (int j = 0; j < r; ++j) cnt += A[j][i];
    if (cnt == r) return 1;
  }
  return 0;
}
bool _1() {
  bool ret = 1;
  for (int i = 0; i < c; ++i) ret &= A[0][i];
  if (ret) return ret;
  ret = 1;
  for (int i = 0; i < c; ++i) ret &= A[r - 1][i];
  if (ret) return ret;
  ret = 1;
  for (int i = 0; i < r; ++i) ret &= A[i][0];
  if (ret) return ret;
  ret = 1;
  for (int i = 0; i < r; ++i) ret &= A[i][c - 1];
  return ret;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> t;
  while (t--) {
    cin >> r >> c;
    int cnt = 0;
    bool corner = 0;
    for (int i = 0; i < r; ++i)
      for (int j = 0; j < c; ++j) {
        char ch;
        cin >> ch;
        A[i][j] = ch == 'A';
        if (i == 0 || i == r - 1 || j == 0 || j == c - 1) corner |= A[i][j];
        cnt += A[i][j];
      }
    if (cnt == 0)
      cout << "MORTAL\n";
    else if (cnt == r * c)
      cout << "0\n";
    else if (_1())
      cout << "1\n";
    else if (A[0][0] || A[0][c - 1] || A[r - 1][0] || A[r - 1][c - 1] ||
             can()) {
      cout << "2\n";
    } else if (corner) {
      cout << "3\n";
    } else {
      cout << "4\n";
    }
  }
  return 0;
}
