#include <bits/stdc++.h>
using namespace std;
char bang[65][65];
int cnt[65];
int coun[65];
int n, m;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int test;
  cin >> test;
  for (int x = 1; x <= test; x++) {
    cin >> n >> m;
    int dem = 0;
    for (int i = 1; i <= n; i++) {
      cnt[i] = 0;
      for (int j = 1; j <= m; j++) {
        cin >> bang[i][j];
        if (bang[i][j] == 'P')
          dem++;
        else
          cnt[i]++;
      }
    }
    for (int i = 1; i <= m; i++) {
      coun[i] = 0;
      for (int j = 1; j <= n; j++)
        if (bang[j][i] == 'A') coun[i]++;
    }
    bool che = 0;
    if (dem == n * m) {
      cout << "MORTAL\n";
      continue;
    } else if (dem == 0) {
      cout << 0 << '\n';
      continue;
    } else {
      int c1 = 0, c2 = 0, c3 = 0, c4 = 0;
      for (int i = 1; i <= m; i++) {
        if (bang[1][i] == 'A') c1++;
        if (bang[n][i] == 'A') c3++;
      }
      for (int i = 1; i <= n; i++) {
        if (bang[i][1] == 'A') c2++;
        if (bang[i][m] == 'A') c4++;
      }
      if (c1 == m || c2 == n || c3 == m || c4 == n) {
        cout << 1 << '\n';
        continue;
      } else {
        for (int i = 2; i < n; i++) {
          if (cnt[i] == m) {
            cout << 2 << '\n';
            che = 1;
            break;
          }
        }
        if (che == 1) continue;
        for (int i = 2; i < m; i++) {
          if (coun[i] == n) {
            cout << 2 << '\n';
            che = 1;
            break;
          }
        }
        if (che == 1) continue;
        if (bang[1][1] == 'A' || bang[1][m] == 'A' || bang[n][1] == 'A' ||
            bang[n][m] == 'A') {
          cout << 2 << '\n';
          continue;
        } else if (c1 >= 1 || c2 >= 1 || c3 >= 1 || c4 >= 1) {
          cout << 3 << '\n';
          continue;
        } else {
          cout << 4 << '\n';
          continue;
        }
      }
    }
  }
}
