#include <bits/stdc++.h>
using namespace std;
using ll = long long;
void run() {
  int n, m;
  cin >> n >> m;
  vector<string> vs;
  vector<vector<int>> v(n + 1, vector<int>(m + 1));
  for (int i = 0; i < n; i++) {
    string s;
    cin >> s;
    vs.push_back(s);
    for (int j = 1; j <= m; j++)
      v[i + 1][j] = (s[j - 1] == 'A') + v[i + 1][j - 1];
  }
  for (int j = 1; j <= m; j++)
    for (int i = 1; i <= n; i++) v[i][j] += v[i - 1][j];
  if (v[n][m] == 0) {
    cout << "MORTAL\n";
    return;
  }
  if (v[n][m] == n * m) {
    cout << "0\n";
    return;
  }
  int mn = 4;
  for (int i = 1; i <= n; i++) {
    bool hor = false;
    if (v[i][m] - v[i - 1][m] == m) hor = true;
    if (hor) {
      mn = 2;
      if (i == 1 || i == n) {
        cout << 1 << endl;
        return;
      }
      if (v[i - 1][m] < (i - 1) * m && (v[n][m] - v[i][m] < (n - i) * m))
        ;
      else {
        cout << 1 << endl;
        return;
      }
    }
  }
  for (int i = 1; i <= m; i++) {
    bool hor = false;
    if (v[n][i] - v[n][i - 1] == n) hor = true;
    if (hor) {
      mn = 2;
      if (i == 1 || i == m) {
        cout << 1 << endl;
        return;
      }
      if (v[n][i - 1] < (i - 1) * n && (v[n][m] - v[n][i] < (m - i) * n))
        ;
      else {
        cout << 1 << endl;
        return;
      }
    }
  }
  if (vs[0][0] == 'A' || vs[0].back() == 'A' || vs.back()[0] == 'A' ||
      vs.back().back() == 'A')
    mn = 2;
  if (mn == 2) {
    cout << 2 << endl;
    return;
  }
  if (v[1][m] > 0 || v[n][m] - v[n - 1][m] > 0 || v[n][1] > 0 ||
      v[n][m] - v[n][m - 1] > 0)
    mn = 3;
  if (mn == 3) {
    cout << 3 << endl;
    return;
  }
  cout << 4 << endl;
  return;
}
int main() {
  int t;
  cin >> t;
  while (t--) {
    run();
  }
}
