#include <bits/stdc++.h>
using namespace std;
string s[70];
int xmove[4] = {0, -1, 0, 1};
int ymove[4] = {-1, 0, 1, 0};
int main() {
  ios::sync_with_stdio(false);
  int t;
  cin >> t;
  while (t--) {
    int r, c;
    cin >> r >> c;
    bool zero = true;
    for (int i = 0; i < r; i++) {
      cin >> s[i];
      for (int j = 0; j < c; j++) {
        if (s[i][j] == 'P') {
          zero = false;
        }
      }
    }
    if (zero) {
      cout << 0 << "\n";
      continue;
    }
    bool poss = false;
    int ans = 4;
    for (int i = 0; i < r; i++) {
      for (int j = 0; j < c; j++) {
        if (s[i][j] == 'A') {
          poss = true;
          break;
        }
      }
    }
    bool onee = true;
    for (int i = 0; i < r; i++) {
      if (s[i][0] == 'P') {
        onee = false;
      }
    }
    if (onee) ans = min(ans, 1);
    onee = true;
    for (int i = 0; i < r; i++) {
      if (s[i][c - 1] == 'P') {
        onee = false;
      }
    }
    if (onee) ans = min(ans, 1);
    onee = true;
    for (int j = 0; j < c; j++) {
      if (s[0][j] == 'P') {
        onee = false;
      }
    }
    if (onee) ans = min(ans, 1);
    onee = true;
    for (int j = 0; j < c; j++) {
      if (s[r - 1][j] == 'P') {
        onee = false;
      }
    }
    if (onee) ans = min(ans, 1);
    if (s[0][0] == 'A' || s[0][c - 1] == 'A' || s[r - 1][0] == 'A' ||
        s[r - 1][c - 1] == 'A') {
      ans = min(ans, 2);
    }
    for (int i = 1; i < r - 1; i++) {
      bool twoos = true;
      for (int j = 0; j < c; j++) {
        if (s[i][j] == 'P') {
          twoos = false;
        }
      }
      if (twoos) {
        ans = min(ans, 2);
      }
    }
    for (int j = 1; j < c - 1; j++) {
      bool twoos = true;
      for (int i = 0; i < r; i++) {
        if (s[i][j] == 'P') {
          twoos = false;
        }
      }
      if (twoos) {
        ans = min(ans, 2);
      }
    }
    for (int i = 1; i < r; i++) {
      if (s[i][0] == 'A') {
        ans = min(ans, 3);
      }
      if (s[i][c - 1] == 'A') {
        ans = min(ans, 3);
      }
    }
    for (int j = 1; j < c; j++) {
      if (s[0][j] == 'A') {
        ans = min(ans, 3);
      }
      if (s[r - 1][j] == 'A') {
        ans = min(ans, 3);
      }
    }
    if (poss == false) {
      cout << "MORTAL\n";
    } else {
      cout << ans << "\n";
    }
  }
  return 0;
}
