#include <bits/stdc++.h>
using namespace std;
const int N = 70;
int t, m, n;
char s[N][N];
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cin >> t;
  while (t--) {
    cin >> m >> n;
    for (int i = 0; i < m; i++)
      for (int j = 0; j < n; j++) cin >> s[i][j];
    bool all = true, no = true;
    for (int i = 0; i < m; i++)
      for (int j = 0; j < n; j++)
        if (s[i][j] == 'P')
          all = false;
        else
          no = false;
    if (all) {
      cout << "0\n";
      continue;
    }
    if (no) {
      cout << "MORTAL\n";
      continue;
    }
    bool side = false, each = true;
    for (int i = 0; i < m; i++)
      if (s[i][0] == 'P') each = false;
    side |= each;
    each = true;
    for (int i = 0; i < m; i++)
      if (s[i][n - 1] == 'P') each = false;
    side |= each;
    each = true;
    for (int i = 0; i < n; i++)
      if (s[0][i] == 'P') each = false;
    side |= each;
    each = true;
    for (int i = 0; i < n; i++)
      if (s[m - 1][i] == 'P') each = false;
    side |= each;
    if (side) {
      cout << "1\n";
      continue;
    }
    side = false;
    for (int i = 0; i < m; i++) {
      bool each = true;
      for (int j = 0; j < n; j++)
        if (s[i][j] == 'P') each = false;
      side |= each;
    }
    for (int i = 0; i < n; i++) {
      bool each = true;
      for (int j = 0; j < m; j++)
        if (s[j][i] == 'P') each = false;
      side |= each;
    }
    if (s[0][0] == 'A' or s[0][n - 1] == 'A' or s[m - 1][0] == 'A' or
        s[m - 1][n - 1] == 'A' or side) {
      cout << "2\n";
      continue;
    }
    side = false, each = false;
    for (int i = 0; i < m; i++)
      if (s[i][0] == 'A') each = true;
    side |= each;
    each = false;
    for (int i = 0; i < m; i++)
      if (s[i][n - 1] == 'A') each = true;
    side |= each;
    each = false;
    for (int i = 0; i < n; i++)
      if (s[0][i] == 'A') each = true;
    side |= each;
    each = false;
    for (int i = 0; i < n; i++)
      if (s[m - 1][i] == 'A') each = true;
    side |= each;
    if (side) {
      cout << "3\n";
      continue;
    } else
      cout << "4\n";
  }
}
