#include <bits/stdc++.h>
using namespace std;
int main() {
  ios::sync_with_stdio(0);
  int t;
  cin >> t;
  while (t--) {
    int n, m;
    cin >> n >> m;
    char a[70][70];
    int A = 0, P = 0;
    for (int i = 1; i <= n; i++) {
      string s;
      cin >> s;
      for (int j = 1; j <= s.size(); j++) {
        a[i][j] = s[j - 1];
        if (a[i][j] == 'A') {
          A++;
        } else {
          P++;
        }
      }
    }
    if (P == 0) {
      cout << 0 << endl;
      continue;
    }
    if (A == 0) {
      cout << "MORTAL" << endl;
      continue;
    }
    int minn = 99999999, flag = 0;
    for (int i = 1; i <= n; i++) {
      if (flag == 1) {
        break;
      }
      for (int j = 1; j <= m; j++) {
        if (a[i][j] == 'A') {
          int x = i, y = j, hen = 1, shu = 1;
          while (x < n) {
            if (a[++x][j] == 'A') shu++;
          }
          while (y < m) {
            if (a[i][++y] == 'A') hen++;
          }
          if (i == 1) {
            if (shu == n) {
              if (j == 1 || j == m) {
                minn = 1;
                flag = 1;
                break;
              } else {
                minn = min(2, minn);
              }
            } else {
              if (j == 1 || j == m) {
                minn = min(2, minn);
              } else {
                minn = min(3, minn);
              }
            }
          } else {
            if (i + shu - 1 == n) {
              if (j == 1 || j == m) {
                minn = min(2, minn);
              } else {
                minn = min(3, minn);
              }
            } else {
              if (j == 1 || j == m) {
                minn = min(3, minn);
              } else {
                minn = min(4, minn);
              }
            }
          }
          if (j == 1) {
            if (hen == m) {
              if (i == 1 || i == n) {
                minn = 1;
                flag = 1;
                break;
              } else {
                minn = min(2, minn);
              }
            } else {
              if (i == 1 || i == n) {
                minn = min(2, minn);
              } else {
                minn = min(3, minn);
              }
            }
          } else {
            if (j + hen - 1 == m) {
              if (i == 1 || i == n) {
                minn = min(2, minn);
              } else {
                minn = min(3, minn);
              }
            } else {
              if (i == 1 || i == n) {
                minn = min(3, minn);
              } else {
                minn = min(4, minn);
              }
            }
          }
        }
      }
    }
    cout << minn << endl;
  }
  return 0;
}
