#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5, M = 2e5 + 5, mx = 1e9, LN = 20, mod = 1e9 + 7;
int ans;
int n, m;
vector<string> v;
bool checkRow(int idx) {
  for (int i = 0; i < m; i++)
    if (v[idx][i] == 'P') return false;
  return true;
}
bool checkCol(int idx) {
  for (int i = 0; i < n; i++)
    if (v[i][idx] == 'P') return false;
  return true;
}
bool checkCorners() {
  if (v[0][0] == 'A' or v[0][m - 1] == 'A' or v[n - 1][0] == 'A' or
      v[n - 1][m - 1] == 'A')
    return true;
  return false;
}
bool anyRow(int idx) {
  for (int i = 0; i < m; i++)
    if (v[idx][i] == 'A') return true;
  return false;
}
bool anyCol(int idx) {
  for (int i = 0; i < n; i++)
    if (v[i][idx] == 'A') return true;
  return false;
}
int solve() {
  cin >> n >> m;
  v.clear();
  v.resize(n);
  for (int i = 0; i < n; i++) {
    cin >> v[i];
  }
  int cells = 0;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
      if (v[i][j] == 'A') ++cells;
  if (cells == 0) return -1;
  if (cells == n * m) return 0;
  if (checkRow(0) or checkRow(n - 1) or checkCol(0) or checkCol(m - 1))
    return 1;
  for (int i = 0; i < n; i++)
    if (checkRow(i)) return 2;
  for (int i = 0; i < m; i++)
    if (checkCol(i)) return 2;
  if (checkCorners()) return 2;
  if (anyRow(0) or anyRow(n - 1) or anyCol(0) or anyCol(m - 1)) return 3;
  return 4;
}
int main() {
  int tests;
  cin >> tests;
  for (int i = 0; i < tests; i++) {
    int res = solve();
    if (res == -1)
      cout << "MORTAL" << endl;
    else
      cout << res << endl;
  }
}
