#include <bits/stdc++.h>
using namespace std;
const int N = 100;
const long long MOD = 1e9 + 7;
char c[N][N];
int t[N], s[N];
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  ;
  int ttt;
  cin >> ttt;
  while (ttt--) {
    int n, m;
    cin >> n >> m;
    int qan = 0;
    memset(t, 0, sizeof(t));
    memset(s, 0, sizeof(s));
    bool bl = false;
    for (int i = 0; i < (n); ++i) {
      for (int j = 0; j < (m); ++j) {
        cin >> c[i][j];
        if (c[i][j] == 'A') {
          t[i]++;
          s[j]++;
          if (t[i] == m || s[j] == n) bl = true;
          qan++;
        }
      }
    }
    if (qan == n * m) {
      cout << 0 << endl;
    } else if (t[0] == m || t[n - 1] == m || s[0] == n || s[m - 1] == n) {
      cout << 1 << endl;
    } else if (c[0][m - 1] == 'A' || c[n - 1][m - 1] == 'A' || c[0][0] == 'A' ||
               c[n - 1][0] == 'A' || bl) {
      cout << 2 << endl;
    } else if (t[0] || t[n - 1] || s[0] || s[m - 1]) {
      cout << 3 << endl;
    } else if (qan) {
      cout << 4 << endl;
    } else {
      cout << "MORTAL" << endl;
    }
  }
  return 0;
}
