#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
const double PI = 3.141592653589793238463;
const int INF = 0x3f3f3f3f;
const int INFS = 1000000000;
const long long LLINF = 9223372036854775807;
const int M = 1000000007;
const int HM = 2147483647;
const int HP = 43;
const double EPS = 1e-3;
signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(NULL);
  cout.tie(NULL);
  int t;
  cin >> t;
  while (t--) {
    int n, m;
    cin >> n >> m;
    bool ok1 = false, ok2 = false, ok3 = false;
    vector<vector<char> > a(n, vector<char>(m));
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        cin >> a[i][j];
        if (a[i][j] == 'A') ok1 = true;
        if (a[i][j] == 'P') ok2 = true;
      }
    }
    for (int i = 0; i < n; i++) {
      bool allr = true;
      for (int j = 0; j < m; j++) {
        if (a[i][j] == 'P') {
          allr = false;
          break;
        }
      }
      if (allr) {
        ok3 = true;
        break;
      }
    }
    for (int j = 0; j < m; j++) {
      bool allc = true;
      for (int i = 0; i < n; i++) {
        if (a[i][j] == 'P') {
          allc = false;
          break;
        }
      }
      if (allc) {
        ok3 = true;
        break;
      }
    }
    int mn, curr = 0;
    bool smn = false, smnOnEdge = false;
    for (int i = 0; i < m; i++) {
      if (a[0][i] == 'P')
        ++curr;
      else {
        smn = true;
        if (i == 0 || i == m - 1) smnOnEdge = true;
      }
    }
    mn = curr;
    curr = 0;
    for (int i = 0; i < m; i++) {
      if (a[n - 1][i] == 'P')
        ++curr;
      else {
        smn = true;
        if (i == 0 || i == m - 1) smnOnEdge = true;
      }
    }
    mn = min(mn, curr);
    curr = 0;
    for (int i = 0; i < n; i++) {
      if (a[i][0] == 'P')
        ++curr;
      else {
        smn = true;
        if (i == 0 || i == n - 1) smnOnEdge = true;
      }
    }
    mn = min(mn, curr);
    curr = 0;
    for (int i = 0; i < n; i++) {
      if (a[i][m - 1] == 'P')
        ++curr;
      else {
        smn = true;
        if (i == 0 || i == n - 1) smnOnEdge = true;
      }
    }
    mn = min(mn, curr);
    curr = 0;
    if (!ok1) {
      cout << "MORTAL" << endl;
    } else if (!ok2) {
      cout << 0 << endl;
    } else if (mn == 0) {
      cout << 1 << endl;
    } else if (smnOnEdge || ok3) {
      cout << 2 << endl;
    } else if (smn) {
      cout << 3 << endl;
    } else {
      cout << 4 << endl;
    }
  }
  return 0;
}
