#include <bits/stdc++.h>
using namespace std;
const int nmsl = 1e9 + 7;
int arr[61];
int arr2[61];
char room[61][61];
int main() {
  int t;
  cin >> t;
  while (t--) {
    int n, m;
    memset(arr, 0, sizeof(arr));
    memset(arr2, 0, sizeof(arr2));
    cin >> n >> m;
    char a;
    int allP = 0;
    int ans = 0x3f3f;
    for (int i = 1; i <= n; i++) {
      int ansP = 0;
      for (int j = 1; j <= m; j++) {
        cin >> room[i][j];
        if (room[i][j] == 'P') {
          ansP++;
          allP++;
          arr[j] -= 1;
          arr2[i] -= 1;
        } else {
          arr[j] += 1;
          arr2[i] += 1;
        }
      }
      if (ansP == 0) {
        if (i == 1 || i == n) {
          ans = min(ans, 1);
        } else {
          ans = min(ans, 2);
        }
      }
    }
    char s = room[1][1], s1 = room[1][m], s2 = room[n][1], s3 = room[n][m];
    for (int i = 1; i <= m; i++) {
      if (arr[i] == n) {
        if (i == 1 || i == m) {
          ans = min(ans, 1);
        } else {
          ans = min(ans, 2);
        }
      } else if (arr[i] != (0 - n)) {
        if ((i == 1 || i == m) &&
            (s == 'A' || s1 == 'A' || s2 == 'A' || s3 == 'A')) {
          ans = min(ans, 2);
        } else {
          ans = min(ans, 3);
        }
      }
    }
    if (arr2[n] == arr2[1] && arr2[1] == -m && arr[1] == arr[m] &&
        arr[1] == -n) {
      ans = 4;
    }
    if (allP == 0) {
      cout << "0" << endl;
    } else {
      if (allP == n * m) {
        cout << "MORTAL" << endl;
        continue;
      }
      cout << ans << endl;
    }
  }
  return 0;
}
