#include <bits/stdc++.h>
using namespace std::chrono;
using namespace std;
int main() {
  long long int t;
  cin >> t;
  while (t--) {
    long long int n, m;
    cin >> n >> m;
    vector<string> v(n);
    for (long long int i = (0); i < (n); i++) {
      cin >> v[i];
    }
    long long int cnt = n * m;
    vector<long long int> row(n, 0), col(m, 0);
    long long int flag = 0;
    for (long long int i = (0); i < (n); i++) {
      for (long long int j = (0); j < (m); j++) {
        if (v[i][j] == 'A') {
          row[i]++;
          col[j]++;
          cnt--;
          flag = 1;
        }
      }
    }
    long long int ans = 0;
    if (cnt == 0) {
      cout << ans << "\n";
      ;
      continue;
    }
    if (flag == 0) {
      cout << "MORTAL\n";
      continue;
    }
    flag = 0;
    for (long long int i = (0); i < (n); i++) {
      if (row[i] == m) {
        flag++;
        break;
      }
    }
    for (long long int i = (0); i < (m); i++) {
      if (col[i] == n) {
        flag = 1;
        break;
      }
    }
    if (flag) {
      if (row[0] == m or row.back() == m or col[0] == n or col.back() == n) {
        cout << 1 << "\n";
        ;
      } else
        cout << 2 << "\n";
      ;
      continue;
    }
    if (v[0][0] == 'A' or v[0].back() == 'A' or v[n - 1][0] == 'A' or
        v[n - 1].back() == 'A') {
      cout << 2 << "\n";
      ;
      continue;
    }
    flag = 0;
    for (long long int i = (0); i < (n); i++) {
      if (v[i][0] == 'A' or v[i].back() == 'A') {
        flag++;
        break;
      }
    }
    for (long long int i = (0); i < (m); i++) {
      if (v[0][i] == 'A' or v[n - 1][i] == 'A') {
        flag++;
        break;
      }
    }
    if (flag) {
      cout << 3 << "\n";
      ;
    } else
      cout << 4 << "\n";
    ;
  }
  return 0;
}
