#include <bits/stdc++.h>
using namespace std;
string s[100];
void solve() {
  int n, m;
  cin >> n >> m;
  bool p = 0, a = 0;
  for (int i = 0; i < n; i++) {
    cin >> s[i];
    for (int j = 0; j < m; j++) {
      if (s[i][j] == 'P') p = 1;
      if (s[i][j] == 'A') a = 1;
    }
  }
  if (!p) {
    cout << 0 << endl;
    return;
  }
  if (!a) {
    cout << "MORTAL" << endl;
    return;
  }
  int mxr = m, mxl = -1;
  bool lin = 0, pre = 0, dot = 0;
  for (int i = 0; i < n; i++) {
    bool ok = 1;
    for (int j = 0; j < m; j++)
      if (s[i][j] == 'P') ok = 0;
    if (ok == 1) {
      if (i == 0 || i == n - 1) {
        cout << 1 << endl;
        return;
      }
      lin = 1;
    }
    if (s[i][0] == 'A') {
      pre = 1;
      for (int j = 0; j < m; j++)
        if (s[i][j] == 'P')
          break;
        else
          mxl = max(mxl, j);
    }
    if (s[i][m - 1] == 'A') {
      pre = 1;
      for (int j = m - 1; j >= 0; j--)
        if (s[i][j] == 'P')
          break;
        else
          mxr = min(mxr, j);
    }
  }
  if (mxl >= mxr) {
    dot = 1;
  }
  mxl = -1, mxr = n;
  for (int i = 0; i < m; i++) {
    bool ok = 1;
    for (int j = 0; j < n; j++)
      if (s[j][i] == 'P') ok = 0;
    if (ok == 1) {
      if (i == 0 || i == m - 1) {
        cout << 1 << endl;
        return;
      }
      lin = 1;
    }
    if (s[0][i] == 'A') {
      pre = 1;
      for (int j = 0; j < n; j++)
        if (s[j][i] == 'P')
          break;
        else
          mxl = max(mxl, j);
    }
    if (s[n - 1][i] == 'A') {
      pre = 1;
      for (int j = n - 1; j >= 0; j--)
        if (s[j][i] == 'P')
          break;
        else
          mxr = min(mxr, j);
    }
  }
  if (mxr <= mxl) dot = 1;
  if (lin || s[0][0] == 'A' || s[0][m - 1] == 'A' || s[n - 1][0] == 'A' ||
      s[n - 1][m - 1] == 'A') {
    cout << 2;
  } else if (pre) {
    cout << 3;
  } else
    cout << 4;
  cout << endl;
}
int main() {
  int t;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
