#include <bits/stdc++.h>
using namespace std;
char a[65][65];
long long r, c;
bool f1() {
  for (long long int i = 0; i < r; i++) {
    for (long long int j = 0; j < c; j++) {
      if (a[i][j] == 'A') {
        return true;
      }
    }
  }
  return false;
}
bool f5() {
  for (long long int i = 0; i < r; i++) {
    for (long long int j = 0; j < c; j++) {
      if (a[i][j] == 'P') return false;
    }
  }
  return true;
}
bool f2() {
  bool flag = true;
  for (long long int i = 0; i < r; i++) {
    if (a[i][0] == 'P') {
      flag = false;
      break;
    }
  }
  if (flag) return true;
  flag = true;
  for (long long int i = 0; i < r; i++) {
    if (a[i][c - 1] == 'P') {
      flag = false;
      break;
    }
  }
  if (flag) return true;
  flag = true;
  for (long long int i = 0; i < c; i++) {
    if (a[0][i] == 'P') {
      flag = false;
      break;
    }
  }
  if (flag) return true;
  flag = true;
  for (long long int i = 0; i < c; i++) {
    if (a[r - 1][i] == 'P') {
      flag = false;
      break;
    }
  }
  if (flag) return true;
  return false;
}
bool f3() {
  if (a[0][0] == 'A' || a[0][c - 1] == 'A' || a[r - 1][0] == 'A' ||
      a[r - 1][c - 1] == 'A')
    return true;
  for (long long int i = 0; i < r; i++) {
    bool flag = true;
    for (long long int j = 0; j < c; j++) {
      if (a[i][j] == 'P') {
        flag = false;
        break;
      }
    }
    if (flag) return true;
  }
  for (long long int j = 0; j < c; j++) {
    bool flag = true;
    for (long long int i = 0; i < r; i++) {
      if (a[i][j] == 'P') {
        flag = false;
        break;
      }
    }
    if (flag) return true;
  }
  return false;
}
bool f4() {
  for (long long int i = 0; i < r; i++) {
    if (a[i][0] == 'A' || a[i][c - 1] == 'A') return true;
  }
  for (long long int i = 0; i < c; i++) {
    if (a[0][i] == 'A' || a[r - 1][i] == 'A') return true;
  }
  return false;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int TESTS = 1;
  cin >> TESTS;
  while (TESTS--) {
    cin >> r >> c;
    for (long long int i = 0; i < r; i++)
      for (long long int j = 0; j < c; j++) cin >> a[i][j];
    if (!f1())
      cout << "MORTAL" << '\n';
    else if (f5())
      cout << 0 << '\n';
    else if (f2())
      cout << 1 << '\n';
    else if (f3())
      cout << 2 << '\n';
    else if (f4())
      cout << 3 << '\n';
    else
      cout << 4 << '\n';
  }
  return 0;
}
