#include <bits/stdc++.h>
using namespace std;
bool all(vector<bool>& x) {
  bool res = true;
  for (int i = 0; i < x.size(); i++) res = res && x[i];
  return res;
}
int main() {
  int t;
  cin >> t;
  while (t--) {
    int r, c, i, j, cnt = 0;
    cin >> r >> c;
    char ch;
    vector<vector<bool> > arr(r, vector<bool>(c));
    for (i = 0; i < r; i++)
      for (j = 0; j < c; j++) {
        cin >> ch;
        arr[i][j] = (ch == 'A');
        if (!arr[i][j]) cnt++;
      }
    if (cnt == r * c) {
      arr.clear();
      cout << "MORTAL\n";
      continue;
    }
    if (cnt == 0) {
      arr.clear();
      cout << "0\n";
      continue;
    }
    vector<bool> b1(c), b3(c), b2(r), b4(r);
    for (i = 0; i < c; i++) {
      b1[i] = arr[0][i];
      b3[i] = arr[r - 1][i];
    }
    for (i = 0; i < r; i++) {
      b2[i] = arr[i][c - 1];
      b4[i] = arr[i][0];
    }
    if (all(b1) || all(b2) || all(b3) || all(b4)) {
      cout << "1\n";
      arr.clear();
      continue;
    }
    bool found = false;
    for (i = 0; i < r; i++) {
      if (all(arr[i]) || all(arr[i])) {
        found = true;
        break;
      }
    }
    vector<bool> tmp(r);
    for (j = 0; j < c; j++) {
      for (i = 0; i < r; i++) tmp[i] = arr[i][j];
      if (all(tmp) || all(tmp)) {
        found = true;
        break;
      }
    }
    if (found || arr[0][0] || arr[0][c - 1] || arr[r - 1][c - 1] ||
        arr[r - 1][0]) {
      cout << "2\n";
      arr.clear();
      continue;
    }
    found = false;
    for (j = 0; j < c; j++)
      if (arr[0][j] || arr[r - 1][j]) found = true;
    for (i = 0; i < r; i++)
      if (arr[i][0] || arr[i][c - 1]) found = true;
    if (found) {
      cout << "3\n";
      arr.clear();
      continue;
    }
    cout << "4\n";
    arr.clear();
  }
}
