#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int t;
  cin >> t;
  for (int i = 0; i < t; i++) {
    int r, c;
    cin >> r >> c;
    vector<string> grid;
    for (int j = 0; j < r; j++) {
      string tmp;
      cin >> tmp;
      grid.push_back(tmp);
    }
    int res = 5;
    bool existsP = false;
    for (int j = 0; j < r; j++) {
      bool ok = true;
      for (int k = 0; k < c; k++) {
        if (grid[j][k] == 'P') {
          ok = false;
          existsP = true;
        }
        if (grid[j][k] == 'A') res = min(res, 4);
        if (grid[j][k] == 'A' && (j == 0 || k == 0 || j == r - 1 || k == c - 1))
          res = min(res, 3);
        if (grid[j][k] == 'A' &&
            ((j == 0 && k == 0) || (j == 0 && k == c - 1) ||
             (j == r - 1 && k == 0) || (j == r - 1 && k == c - 1)))
          res = min(res, 2);
      }
      if (ok) res = min(res, 2);
      if (ok && (j == 0 || j == r - 1)) res = min(res, 1);
    }
    for (int k = 0; k < c; k++) {
      bool ok = true;
      for (int j = 0; j < r; j++) {
        if (grid[j][k] == 'P') ok = false;
      }
      if (ok) res = min(res, 2);
      if (ok && (k == 0 || k == c - 1)) res = min(res, 1);
    }
    if (!existsP) res = 0;
    if (res == 5)
      cout << "MORTAL\n";
    else
      cout << res << '\n';
  }
}
