#include <bits/stdc++.h>
using namespace std;
const int N = 100;
int n, m;
int g[N][N];
int checkinf() {
  int flag = 0;
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j)
      if (g[i][j]) flag = 1;
  return !flag;
}
int check1() {
  int flag = 1;
  for (int i = 1; i <= n; ++i) flag &= g[i][1];
  if (flag) return 1;
  flag = 1;
  for (int i = 1; i <= n; ++i) flag &= g[i][m];
  if (flag) return 1;
  flag = 1;
  for (int i = 1; i <= m; ++i) flag &= g[1][i];
  if (flag) return 1;
  flag = 1;
  for (int i = 1; i <= m; ++i) flag &= g[n][i];
  if (flag) return 1;
  return 0;
}
int check2() {
  if (g[1][1] || g[n][1] || g[1][m] || g[n][m]) return 1;
  for (int i = 1; i <= n; ++i) {
    int flag = 1;
    for (int j = 1; j <= m; ++j) flag &= g[i][j];
    if (flag) return 1;
  }
  for (int i = 1; i <= m; ++i) {
    int flag = 1;
    for (int j = 1; j <= n; ++j) flag &= g[j][i];
    if (flag) return 1;
  }
  return 0;
}
int check3() {
  int flag = 0;
  for (int i = 1; i <= n; ++i) flag |= g[i][1];
  for (int i = 1; i <= n; ++i) flag |= g[i][m];
  for (int i = 1; i <= m; ++i) flag |= g[1][i];
  for (int i = 1; i <= m; ++i) flag |= g[n][i];
  return flag;
}
int check4() {
  int flag = 0;
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j) flag |= g[i][j];
  return flag;
}
int check0() {
  int flag = 1;
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j) flag &= g[i][j];
  return flag;
}
void solve() {
  cin >> n >> m;
  string s;
  for (int i = 1; i <= n; ++i) {
    cin >> s;
    for (int j = 0; j < m; ++j) g[i][j + 1] = (s[j] == 'A');
  }
  if (check0())
    puts("0");
  else if (checkinf())
    puts("MORTAL");
  else if (check1())
    puts("1");
  else if (check2())
    puts("2");
  else if (check3())
    puts("3");
  else if (check4())
    puts("4");
}
int main() {
  ios::sync_with_stdio(0);
  int T;
  cin >> T;
  while (T--) solve();
}
