#include <bits/stdc++.h>
using namespace std;
int r, c;
vector<string> mat;
bool all_hor(int i) {
  for (int j = 0; j < c; ++j)
    if (mat[i][j] != 'A') return false;
  return true;
}
bool all_ver(int j) {
  for (int i = 0; i < r; ++i)
    if (mat[i][j] != 'A') return false;
  return true;
}
bool has_all_hor() {
  for (int i = 0; i < r; ++i)
    if (all_hor(i)) return true;
  return false;
}
bool has_all_ver() {
  for (int j = 0; j < c; ++j)
    if (all_ver(j)) return true;
  return false;
}
bool has_corner() {
  return mat[0][0] == 'A' || mat[0][c - 1] == 'A' || mat[r - 1][0] == 'A' ||
         mat[r - 1][c - 1] == 'A';
}
bool has_hor(int i) {
  for (int j = 0; j < c; ++j)
    if (mat[i][j] == 'A') return true;
  return false;
}
bool has_ver(int j) {
  for (int i = 0; i < r; ++i)
    if (mat[i][j] == 'A') return true;
  return false;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(NULL);
  int T;
  cin >> T;
  while (T--) {
    cin >> r >> c;
    mat.assign(r, "");
    int total_a = 0;
    for (string &s : mat) {
      cin >> s;
      for (char &c : s) total_a += c == 'A';
    }
    if (total_a == 0) {
      cout << "MORTAL\n";
    } else if (total_a == r * c) {
      cout << 0 << "\n";
    } else if (all_hor(0) || all_ver(0) || all_hor(r - 1) || all_ver(c - 1)) {
      cout << 1 << "\n";
    } else if (has_all_hor() || has_all_ver() || has_corner()) {
      cout << 2 << "\n";
    } else if (has_hor(0) || has_ver(0) || has_hor(r - 1) || has_ver(c - 1)) {
      cout << 3 << "\n";
    } else {
      cout << 4 << "\n";
    }
  }
}
