#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9 + 7;
const int MOD = 1e9 + 7;
const int dx[4] = {0, 0, -1, 1};
const int dy[4] = {-1, 1, 0, 0};
const int N = 101;
int n, m, a[N][N], psum[N][N], T;
bool Check_1() {
  if (psum[1][m] == 0) return true;
  if (psum[n][1] == 0) return true;
  if (psum[n][m] - psum[n - 1][m] == 0) return true;
  if (psum[n][m] - psum[n][m - 1] == 0) return true;
  return false;
}
bool Check_2() {
  if (a[1][1] == 0 || a[1][m] == 0 || a[n][1] == 0 || a[n][m] == 0) return true;
  for (int i = 2; i < n; i++) {
    if (psum[i][m] - psum[i - 1][m] == 0) return true;
  }
  for (int i = 2; i < m; i++) {
    if (psum[n][i] - psum[n][i - 1] == 0) return true;
  }
  return false;
}
bool Check_3() {
  for (int i = 2; i < n; i++) {
    if (a[i][1] == 0 || a[i][m] == 0) return true;
  }
  for (int i = 2; i < m; i++) {
    if (a[1][i] == 0 || a[n][i] == 0) return true;
  }
  return false;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> T;
  while (T--) {
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
      for (int j = 1; j <= m; j++) {
        char c;
        cin >> c;
        int x = 0;
        if (c == 'P') x = 1;
        psum[i][j] = psum[i - 1][j] + psum[i][j - 1] - psum[i - 1][j - 1] + x;
        a[i][j] = x;
      }
    }
    if (psum[n][m] == n * m) {
      cout << "MORTAL\n";
      continue;
    }
    if (psum[n][m] == 0) {
      cout << 0 << '\n';
      continue;
    }
    if (Check_1())
      cout << 1 << '\n';
    else if (Check_2())
      cout << 2 << '\n';
    else if (Check_3())
      cout << 3 << '\n';
    else
      cout << 4 << '\n';
  }
  return 0;
}
