#include <bits/stdc++.h>
using namespace std;
void input() {}
void solve() {
  long long int n, m;
  cin >> n >> m;
  long long int a[n][m];
  long long int flag = 1, temp = 0;
  for (long long int i = 0; i < n; i++) {
    for (long long int j = 0; j < m; j++) {
      char ch;
      cin >> ch;
      if (ch == 'A') {
        a[i][j] = 1;
      } else {
        a[i][j] = 0;
      }
      if (a[i][j]) {
        flag = 0;
      }
      temp += a[i][j];
    }
  }
  if (temp == n * m) {
    cout << "0";
    return;
  }
  if (flag) {
    cout << "MORTAL";
    return;
  }
  for (long long int i = 0; i < 1; i++) {
    long long int cnt1 = 0, cnt2 = 0;
    for (long long int j = 0; j < m; j++) {
      if (a[0][j]) {
        cnt1++;
      }
      if (a[n - 1][j]) {
        cnt2++;
      }
    }
    if (cnt1 == m || cnt2 == m) {
      cout << "1";
      return;
    }
  }
  for (long long int j = 0; j < 1; j++) {
    long long int cnt1 = 0, cnt2 = 0;
    for (long long int i = 0; i < n; i++) {
      if (a[i][0]) {
        cnt1++;
      }
      if (a[i][m - 1]) {
        cnt2++;
      }
    }
    if (cnt1 == n || cnt2 == n) {
      cout << "1";
      return;
    }
  }
  for (long long int i = 1; i < n - 1; i++) {
    long long int cnt = 0;
    for (long long int j = 0; j < m; j++) {
      if (a[i][j]) {
        cnt++;
      }
    }
    if (cnt == m) {
      cout << "2";
      return;
    }
  }
  for (long long int j = 1; j < m - 1; j++) {
    long long int cnt = 0;
    for (long long int i = 0; i < n; i++) {
      if (a[i][j]) {
        cnt++;
      }
    }
    if (cnt == n) {
      cout << "2";
      return;
    }
  }
  if (a[0][m - 1] || a[0][0] || a[n - 1][0] || a[n - 1][m - 1]) {
    cout << "2";
    return;
  }
  long long int cnt = 0;
  for (long long int i = 0; i < n; i++) {
    cnt += a[i][0];
    cnt += a[i][m - 1];
  }
  for (long long int i = 0; i < m; i++) {
    cnt += a[0][i];
    cnt += a[n - 1][i];
  }
  if (cnt) {
    cout << "3";
  } else {
    cout << "4";
  }
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  input();
  int t = 1, i = 1;
  cin >> t;
  while (t--) {
    solve();
    cout << "\n";
  }
}
