#include <bits/stdc++.h>
using namespace std;
const int MAX = 2e5 + 6;
const int INF = 1e9;
const long long MOD = 1e9 + 7;
int solve() {
  int r, c;
  cin >> r >> c;
  char grid[r + 1][c + 1];
  int row[r + 1], col[c + 1];
  int cntp = 0, edge = 0;
  for (int i = 1; i <= r; i++) {
    for (int j = 1; j <= c; j++) {
      cin >> grid[i][j];
      if (grid[i][j] == 'P')
        cntp++;
      else {
        if (i == 1 or j == 1 or i == r or j == c) edge = 1;
      }
    }
  }
  if (cntp == r * c) return -1;
  if (cntp == 0) return 0;
  for (int i = 1; i <= r; i++) {
    row[i] = 1;
    for (int j = 1; j <= c; j++)
      if (grid[i][j] == 'P') row[i] = 0;
  }
  for (int i = 1; i <= c; i++) {
    col[i] = 1;
    for (int j = 1; j <= r; j++)
      if (grid[j][i] == 'P') col[i] = 0;
  }
  if (row[1] or row[r] or col[1] or col[c]) return 1;
  for (int i = 1; i <= r; i++)
    if (row[i]) return 2;
  for (int i = 1; i <= c; i++)
    if (col[i]) return 2;
  if (grid[1][1] == 'A' or grid[1][c] == 'A' or grid[r][1] == 'A' or
      grid[r][c] == 'A')
    return 2;
  else
    return 4 - edge;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int t;
  cin >> t;
  while (t--) {
    int ans = solve();
    if (ans == -1)
      cout << "MORTAL\n";
    else
      cout << ans << "\n";
  }
}
