#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
  int val;
  TreeNode* left;
  TreeNode* right;
  TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
struct ListNode {
  int val;
  ListNode* next;
  ListNode(int x) : val(x), next(NULL) {}
};
struct cmp {
  bool operator()(const ListNode* a, const ListNode* b) {
    return a->val > b->val;
  }
};
bool checkLine(vector<vector<char> >& v, pair<int, int> start,
               pair<int, int> end) {
  bool isLine = true;
  for (int i = start.first; i <= end.first; i++)
    if (v[i][start.second] != 'A') {
      isLine = false;
      break;
    }
  for (int i = start.second; i <= end.second; i++)
    if (v[start.first][i] != 'A') {
      isLine = false;
      break;
    }
  return isLine;
}
int main() {
  int n;
  cin >> n;
  while (n--) {
    int a, b;
    cin >> a >> b;
    vector<vector<char> > array(a, vector<char>(b, 'a'));
    bool isAllA = true;
    bool isAllP = true;
    for (int i = 0; i < a; i++)
      for (int j = 0; j < b; j++) {
        cin >> array[i][j];
        if (isAllA) isAllA &= (array[i][j] == 'A');
        if (isAllP) isAllP &= (array[i][j] == 'P');
      }
    if (isAllA || isAllP) {
      if (isAllA)
        cout << "0" << endl;
      else
        cout << "MORTAL" << endl;
      continue;
    }
    bool isCorner = (array[0][0] == 'A' || array[0][b - 1] == 'A' ||
                     array[a - 1][0] == 'A' || array[a - 1][b - 1] == 'A');
    if (isCorner) {
      if (checkLine(array, pair<int, int>(0, 0), pair<int, int>(0, b - 1)) ||
          checkLine(array, pair<int, int>(0, 0), pair<int, int>(a - 1, 0)) ||
          checkLine(array, pair<int, int>(a - 1, 0),
                    pair<int, int>(a - 1, b - 1)) ||
          checkLine(array, pair<int, int>(0, b - 1),
                    pair<int, int>(a - 1, b - 1)))
        cout << "1" << endl;
      else
        cout << "2" << endl;
    } else {
      int times = 4;
      for (int i = 1; i < a - 1; i++)
        if (array[i][0] == 'A' || array[i][b - 1] == 'A') {
          times = min(times, 3);
          for (int j = 0; j < b; j++) {
            if (array[i][j] != 'A') break;
            if (j == b - 1) times = min(times, 2);
          }
        }
      for (int i = 1; i < b - 1; i++)
        if (array[0][i] == 'A' || array[a - 1][i] == 'A') {
          times = min(times, 3);
          for (int j = 0; j < a; j++) {
            if (array[j][i] != 'A') break;
            if (j == a - 1) times = min(times, 2);
          }
        }
      cout << times << endl;
    }
  }
}
