#include <bits/stdc++.h>
using namespace std;
const int maxn = 65;
char s[maxn][maxn];
int main() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int m, n;
    scanf("%d%d", &m, &n);
    for (int i = 0; i < m; i++) {
      scanf("%s", s[i]);
    }
    int ans = 100;
    for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {
        if (s[i][j] == 'A') {
          ans = min(ans, 4);
          break;
        }
      }
    }
    for (int i = 0; i < m; i++) {
      if (s[i][0] == 'A' || s[i][n - 1] == 'A') {
        ans = min(ans, 3);
        break;
      }
    }
    for (int i = 0; i < n; i++) {
      if (s[0][i] == 'A' || s[m - 1][i] == 'A') {
        ans = min(ans, 3);
        break;
      }
    }
    if (s[0][0] == 'A' || s[0][n - 1] == 'A' || s[m - 1][0] == 'A' ||
        s[m - 1][n - 1] == 'A') {
      ans = min(ans, 2);
    }
    int ok = 1;
    for (int i = 0; i < m; i++) {
      if (s[i][0] != 'A') {
        ok = 0;
        break;
      }
    }
    if (ok) {
      ans = min(ans, 1);
    }
    for (int i = 0; i < m; i++) {
      ok = 1;
      for (int j = 0; j < n; j++) {
        if (s[i][j] != 'A') {
          ok = 0;
          break;
        }
      }
      if (ok) {
        ans = min(ans, 2);
        break;
      }
    }
    for (int i = 0; i < n; i++) {
      ok = 1;
      for (int j = 0; j < m; j++) {
        if (s[j][i] != 'A') {
          ok = 0;
          break;
        }
      }
      if (ok) {
        ans = min(ans, 2);
        break;
      }
    }
    ok = 1;
    for (int i = 0; i < m; i++) {
      if (s[i][n - 1] != 'A') {
        ok = 0;
        break;
      }
    }
    if (ok) {
      ans = min(ans, 1);
    }
    ok = 1;
    for (int i = 0; i < n; i++) {
      if (s[0][i] != 'A') {
        ok = 0;
        break;
      }
    }
    if (ok) {
      ans = min(ans, 1);
    }
    ok = 1;
    for (int i = 0; i < n; i++) {
      if (s[m - 1][i] != 'A') {
        ok = 0;
        break;
      }
    }
    if (ok) {
      ans = min(ans, 1);
    }
    ok = 1;
    for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {
        if (s[i][j] != 'A') {
          ok = 0;
          break;
        }
      }
    }
    if (ok) {
      ans = min(ans, 0);
    }
    if (ans == 100) {
      printf("MORTAL\n");
    } else {
      printf("%d\n", ans);
    }
  }
}
