#include <bits/stdc++.h>
using namespace std;
long long n, m, k, q, bo, ans;
long long x[3000010], y[3000010];
char ch;
int main() {
  cin >> q;
  while (q--) {
    cin >> n >> m;
    ans = 5;
    bo = 0;
    for (int i = 1; i <= n; i++) {
      x[i] = 0;
    }
    for (int j = 1; j <= m; j++) {
      y[j] = 0;
    }
    for (int i = 1; i <= n; i++) {
      for (int j = 1; j <= m; j++) {
        cin >> ch;
        if (ch == 'P') {
          bo = 1;
          continue;
        }
        ans = min(ans, 4ll);
        if (i == 1 && j == 1 || i == 1 && j == m || i == n && j == 1 ||
            i == n && j == m) {
          ans = min(ans, 2ll);
        }
        x[i]++;
        y[j]++;
        if (i == 1 || i == n || j == 1 || j == m) {
          ans = min(ans, 3ll);
        }
      }
    }
    for (int i = 1; i <= n; i++) {
      if (x[i] == m) {
        ans = min(ans, 2ll);
      }
    }
    if (x[1] == m || x[n] == m) {
      ans = min(ans, 1ll);
    }
    for (int j = 1; j <= m; j++) {
      if (y[j] == n) {
        ans = min(ans, 2ll);
      }
    }
    if (y[1] == n || y[m] == n) {
      ans = min(ans, 1ll);
    }
    if (bo == 0) {
      ans = 0;
    }
    if (ans == 5) {
      cout << "MORTAL" << endl;
    } else {
      cout << ans << endl;
    }
  }
  return 0;
}
