#include <bits/stdc++.h>
using namespace std;
char a[101][101];
int t, n, m;
bool check_row(int x) {
  for (int i = 1; i <= m; i++)
    if (a[x][i] == 'P') return false;
  return true;
}
bool check_column(int x) {
  for (int i = 1; i <= n; i++)
    if (a[i][x] == 'P') return false;
  return true;
}
bool check_complete() {
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++)
      if (a[i][j] == 'P') return false;
  return true;
}
bool check_mortal() {
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++)
      if (a[i][j] == 'A') return false;
  return true;
}
bool check_situation1() {
  if (check_row(1)) return true;
  if (check_row(n)) return true;
  if (check_column(1)) return true;
  if (check_column(m)) return true;
  return false;
}
bool check_situation2() {
  if (a[1][1] == 'A' || a[1][m] == 'A' || a[n][1] == 'A' || a[n][m] == 'A')
    return true;
  for (int i = 2; i < n; i++)
    if (check_row(i)) return true;
  for (int i = 2; i < m; i++)
    if (check_column(i)) return true;
  return false;
}
bool check_situation3() {
  for (int i = 1; i <= n; i++)
    if (a[i][1] == 'A' || a[i][m] == 'A') return true;
  for (int i = 1; i <= m; i++)
    if (a[1][i] == 'A' || a[n][i] == 'A') return true;
  return false;
}
int main() {
  cin >> t;
  while (t--) {
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
      for (int j = 1; j <= m; j++) cin >> a[i][j];
    if (check_complete())
      printf("0\n");
    else if (check_mortal())
      printf("MORTAL\n");
    else if (check_situation1())
      printf("1\n");
    else if (check_situation2())
      printf("2\n");
    else if (check_situation3())
      printf("3\n");
    else
      printf("4\n");
  }
}
