#include <bits/stdc++.h>
using namespace std;
const long long int N = 1e6 + 9;
const long long int p = 31;
const long long int m = 1e9 + 7;
const long long int inf = 1e14;
long long int mod = 1e9 + 7;
long long int powm(long long int a, long long int b) {
  long long int res = 1;
  while (b) {
    if (b & 1) res = (res * a) % mod;
    a = (a * a) % mod;
    b >>= 1;
  }
  return res;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long int t = 1;
  cin >> t;
  while (t--) {
    long long int r, c;
    cin >> r >> c;
    string a[r];
    for (int i = 0; i < r; i++) {
      cin >> a[i];
    }
    bool is_a = 0;
    for (int i = 0; i < r; i++) {
      for (int j = 0; j < c; j++) {
        if (a[i][j] == 'A') is_a = 1;
      }
      if (is_a) break;
    }
    if (is_a) {
      bool all = 1;
      for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
          if (a[i][j] != 'A') all = 0;
        }
      }
      if (all) {
        cout << 0 << '\n';
      } else {
        bool one[4] = {1, 1, 1, 1};
        for (int i = 0; i < r; i++) {
          if (a[i][0] != 'A') one[0] = 0;
          if (a[i][c - 1] != 'A') one[1] = 0;
        }
        for (int i = 0; i < c; i++) {
          if (a[0][i] != 'A') one[2] = 0;
          if (a[r - 1][i] != 'A') one[3] = 0;
        }
        bool tw = 0;
        for (int i = 0; i < r; i++) {
          bool s = 1;
          for (int j = 0; j < c; j++) {
            if (a[i][j] != 'A') s = 0;
          }
          if (s) {
            tw = 1;
            break;
          }
        }
        for (int j = 0; j < c; j++) {
          bool s = 1;
          for (int i = 0; i < r; i++) {
            if (a[i][j] != 'A') s = 0;
          }
          if (s) {
            tw = 1;
            break;
          }
        }
        if (one[0] || one[1] || one[2] || one[3]) {
          cout << 1 << '\n';
        } else if (a[0][0] == 'A' || a[0][c - 1] == 'A' || a[r - 1][0] == 'A' ||
                   a[r - 1][c - 1] == 'A' || tw) {
          cout << 2 << '\n';
        } else {
          bool th = 0;
          for (int i = 0; i < c; i++) {
            if (a[0][i] == 'A') th = 1;
            if (a[r - 1][i] == 'A') th = 1;
          }
          for (int i = 0; i < r; i++) {
            if (a[i][0] == 'A') th = 1;
            if (a[i][c - 1] == 'A') th = 1;
          }
          if (th) {
            cout << 3 << '\n';
          } else {
            cout << 4 << '\n';
          }
        }
      }
    } else {
      cout << "MORTAL" << '\n';
    }
  }
}
