#include <bits/stdc++.h>
using namespace std;
int t, r, c;
string g[61];
int row[61], col[61];
int main() {
  ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
  cin >> t;
  for (int _ = (0); _ < (t); ++_) {
    cin >> r >> c;
    memset(row, 0, sizeof(row));
    memset(col, 0, sizeof(col));
    for (int i = (0); i < (r); ++i) cin >> g[i];
    int tot = 0;
    for (int i = (0); i < (r); ++i)
      for (int j = (0); j < (c); ++j) {
        if (g[i][j] == 'A') {
          ++tot;
          ++row[i];
          ++col[j];
        }
      }
    if (tot == 0) {
      cout << "MORTAL\n";
      continue;
    }
    if (tot == r * c) {
      cout << 0 << "\n";
      continue;
    }
    int ans = 4;
    int mxr = 0, mxc = 0;
    for (int i = (0); i < (r); ++i) mxr = max(mxr, row[i]);
    for (int i = (0); i < (c); ++i) mxc = max(mxc, col[i]);
    if (row[0] == c || row[r - 1] == c || col[0] == r || col[c - 1] == r)
      ans = 1;
    else if (g[0][0] == 'A' || g[r - 1][c - 1] == 'A' || mxr == c || mxc == r ||
             g[0][c - 1] == 'A' || g[r - 1][0] == 'A')
      ans = 2;
    else if (row[0] > 0 || row[r - 1] > 0 || col[0] > 0 || col[c - 1] > 0)
      ans = 3;
    cout << ans << "\n";
  }
  return 0;
}
