#include <bits/stdc++.h>
using namespace std;
const int mod = (1e9) + 7;
int t, n, m, sum[65][65], x[65][65];
bool k[4];
char ch;
int calc(int a, int b, int c, int d) {
  return sum[c][d] - sum[a - 1][d] - sum[c][b - 1] + sum[a - 1][b - 1];
}
int main() {
  cin >> t;
  while (t--) {
    cin >> n >> m;
    memset(sum, 0, sizeof(sum));
    for (int i = 1; i <= n; i++)
      for (int j = 1; j <= m; j++) {
        cin >> ch;
        sum[i][j] =
            sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1] + (ch == 'A');
        x[i][j] = (ch == 'A');
      }
    if (sum[n][m] == 0) {
      cout << "MORTAL\n";
      continue;
    }
    if (sum[n][m] == n * m) {
      cout << "0\n";
      continue;
    }
    for (int i = 0; i < 4; i++) k[i] = 0;
    for (int i = 1; i <= n; i++) {
      if (calc(1, 1, i, m) == i * m) k[1] = 1;
      if (calc(i, 1, n, m) == (n - i + 1) * m) k[1] = 1;
      if (x[i][1] || x[i][m]) k[3] = 1;
    }
    for (int j = 1; j <= m; j++) {
      if (calc(1, 1, n, j) == n * j) k[1] = 1;
      if (calc(1, j, n, m) == (m - j + 1) * n) k[1] = 1;
      if (x[1][j] || x[n][j]) k[3] = 1;
    }
    for (int i = 1; i <= n; i++)
      for (int j = 1; j <= i; j++)
        if (calc(j, 1, i, m) == (i - j + 1) * m) k[2] = 1;
    for (int j = 1; j <= m; j++)
      for (int i = 1; i <= j; i++)
        if (calc(1, i, n, j) == (j - i + 1) * n) k[2] = 1;
    if (x[1][1] || x[n][1] || x[1][m] || x[n][m]) k[2] = 1;
    if (k[1])
      cout << 1;
    else if (k[2])
      cout << 2;
    else if (k[3])
      cout << 3;
    else
      cout << 4;
    cout << "\n";
  }
  return 0;
}
