#include <bits/stdc++.h>
using namespace std;
const int N = 500005, mod = 1000000007;
long long int a, b, c, d, e, f, g, h[N], arr[N];
vector<long long int> v;
char s[100][100];
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  cin >> g;
  while (g--) {
    cin >> a >> b;
    bool flag = 1, flag2 = 1;
    for (long long int i = 1; i <= a; i++) {
      for (long long int j = 1; j <= b; j++) {
        cin >> s[i][j];
        if (s[i][j] == 'P') flag = 0;
        if (s[i][j] == 'A') flag2 = 0;
      }
    }
    if (flag == 1) {
      cout << 0 << endl;
      continue;
    }
    if (flag2 == 1) {
      cout << "MORTAL" << endl;
      continue;
    }
    flag = 1;
    for (long long int i = 1; i <= b; i++)
      if (s[1][i] == 'P') flag = 0;
    if (flag == 1) {
      cout << 1 << endl;
      continue;
    }
    flag = 1;
    for (long long int i = 1; i <= a; i++)
      if (s[i][1] == 'P') flag = 0;
    if (flag == 1) {
      cout << 1 << endl;
      continue;
    }
    flag = 1;
    for (long long int i = 1; i <= b; i++)
      if (s[a][i] == 'P') flag = 0;
    if (flag == 1) {
      cout << 1 << endl;
      continue;
    }
    flag = 1;
    for (long long int i = 1; i <= a; i++)
      if (s[i][b] == 'P') flag = 0;
    if (flag == 1) {
      cout << 1 << endl;
      continue;
    }
    if (s[1][1] == 'A' or s[1][b] == 'A' or s[a][1] == 'A' or s[a][b] == 'A') {
      cout << 2 << endl;
      continue;
    }
    flag2 = 0;
    for (long long int i = 2; i < a; i++) {
      flag = 1;
      for (long long int j = 1; j <= b; j++) {
        if (s[i][j] == 'P') flag = 0;
      }
      if (flag == 1) {
        cout << 2 << endl;
        flag2 = 1;
        break;
      }
    }
    if (flag2 == 1) continue;
    flag2 = 0;
    for (long long int i = 2; i < b; i++) {
      flag = 1;
      for (long long int j = 1; j <= a; j++) {
        if (s[j][i] == 'P') flag = 0;
      }
      if (flag == 1) {
        cout << 2 << endl;
        flag2 = 1;
        break;
      }
    }
    if (flag2 == 1) continue;
    flag = 0;
    for (long long int i = 2; i < b; i++)
      if (s[1][i] == 'A') flag = 1;
    for (long long int i = 2; i < b; i++)
      if (s[a][i] == 'A') flag = 1;
    for (long long int i = 2; i < a; i++)
      if (s[i][1] == 'A') flag = 1;
    for (long long int i = 2; i < a; i++)
      if (s[i][b] == 'A') flag = 1;
    if (flag == 1) {
      cout << 3 << endl;
      continue;
    }
    cout << 4 << endl;
  }
}
