#include <bits/stdc++.h>
using namespace std;
int64_t mod = 1e9 + 7;
int64_t mod1 = 1e9 + 6;
int64_t power(int64_t a, int64_t b) {
  if (b == 0)
    return 1;
  else if (b % 2 == 0)
    return power((((a % mod) * (a % mod)) % mod), b / 2) % mod;
  else
    return ((a % mod) * (power((((a % mod) * (a % mod)) % mod), b / 2) % mod)) %
           mod;
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  int64_t t;
  cin >> t;
  while (t--) {
    int64_t n, m;
    cin >> n >> m;
    int64_t a[n + 1][m + 1];
    int64_t ch = 0, ch1 = 0;
    for (int64_t i = 1; i <= n; ++i) {
      for (int64_t j = 1; j <= m; ++j) {
        char ch5;
        cin >> ch5;
        if (ch5 == 'A') {
          a[i][j] = 1;
          ch = 1;
        } else {
          a[i][j] = 0;
          ch1 = 1;
        }
      }
    }
    if (ch == 0) {
      cout << "MORTAL" << '\n';
      continue;
    }
    if (ch1 == 0) {
      cout << 0 << '\n';
      continue;
    }
    int64_t ans = -1;
    int64_t che = 0;
    for (int64_t j = 1; j <= m; ++j) {
      if (a[1][j] == 0) {
        che = 1;
        break;
      }
    }
    if (che == 0) {
      ans = 1;
    }
    che = 0;
    for (int64_t j = 1; j <= m; ++j) {
      if (a[n][j] == 0) {
        che = 1;
      }
    }
    if (che == 0) {
      ans = 1;
    }
    che = 0;
    for (int64_t j = 1; j <= n; ++j) {
      if (a[j][m] == 0) {
        che = 1;
      }
    }
    if (che == 0) {
      ans = 1;
    }
    che = 0;
    for (int64_t j = 1; j <= n; ++j) {
      if (a[j][1] == 0) {
        che = 1;
      }
    }
    if (che == 0) {
      ans = 1;
    }
    if (ans == 1) {
      cout << 1 << '\n';
      continue;
    }
    if (a[1][1] == 1 or a[n][1] == 1 or a[1][m] == 1 or a[n][m] == 1) {
      cout << 2 << '\n';
      continue;
    }
    for (int64_t i = 2; i <= n - 1; ++i) {
      che = 0;
      for (int64_t j = 1; j <= m; ++j) {
        if (a[i][j] == 0) {
          che = 1;
          break;
        }
      }
      if (che == 0) {
        ans = 2;
        break;
      }
    }
    for (int64_t i = 2; i <= m - 1; ++i) {
      che = 0;
      for (int64_t j = 1; j <= n; ++j) {
        if (a[j][i] == 0) {
          che = 1;
          break;
        }
      }
      if (che == 0) {
        ans = 2;
        break;
      }
    }
    if (ans == 2) {
      cout << 2 << '\n';
      continue;
    }
    for (int64_t i = 2; i <= n - 1; ++i) {
      che = 0;
      if (a[i][1] == 1 or a[i][m] == 1) {
        ans = 3;
        break;
      }
    }
    for (int64_t i = 2; i <= m - 1; ++i) {
      if (a[1][i] == 1 or a[n][i] == 1) {
        ans = 3;
        break;
      }
    }
    if (ans == 3) {
      cout << 3 << '\n';
      continue;
    }
    cout << 4 << '\n';
    continue;
  }
}
