#include <bits/stdc++.h>
using namespace std;
const int M = 1000000007;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int t;
  cin >> t;
  while (t--) {
    int r, c, cta = 0;
    cin >> r >> c;
    string s[r];
    for (int i = 0; i < r; i++) cin >> s[i];
    for (int i = 0; i < r; i++) {
      for (int j = 0; j < c; j++) {
        if (s[i][j] == 'A') cta++;
      }
    }
    if (cta == r * c) {
      cout << "0\n";
      continue;
    }
    if (cta == 0) {
      cout << "MORTAL\n";
      continue;
    }
    int left = 0, right = 0, up = 0, down = 0;
    for (int i = 0; i < r; i++) {
      if (s[i][0] == 'A') left++;
      if (s[i][c - 1] == 'A') right++;
    }
    for (int i = 0; i < c; i++) {
      if (s[0][i] == 'A') up++;
      if (s[r - 1][i] == 'A') down++;
    }
    if (left == r || right == r || up == c || down == c) {
      cout << "1\n";
      continue;
    }
    if (s[0][0] == 'A' || s[r - 1][0] == 'A' || s[0][c - 1] == 'A' ||
        s[r - 1][c - 1] == 'A') {
      cout << "2\n";
      continue;
    }
    int jhanda = 0;
    for (int ii = 0; ii < c; ii++) {
      int ct1 = 0;
      for (int i = 0; i < r; i++)
        if (s[i][ii] == 'A') ct1++;
      if (ct1 == r) {
        cout << "2\n";
        jhanda = 1;
        break;
      }
    }
    if (jhanda) continue;
    for (int i = 0; i < r; i++) {
      int ct = 0;
      for (int j = 0; j < c; j++)
        if (s[i][j] == 'A') ct++;
      if (ct == c) {
        cout << "2\n";
        jhanda = 1;
        break;
      }
    }
    if (jhanda) continue;
    if (left || right || up || down) {
      cout << "3\n";
      continue;
    }
    cout << "4\n";
  }
}
