#include <bits/stdc++.h>
using namespace std;
template <typename T, typename V>
ostream &operator<<(ostream &out, const pair<T, V> x) {
  out << "{" << x.first << " : " << x.second << "}";
  return out;
}
template <typename T>
ostream &operator<<(ostream &out, const set<T> x) {
  for (auto &it : x) {
    out << it << " ";
  }
  return out;
}
template <typename T>
ostream &operator<<(ostream &out, const multiset<T> x) {
  for (auto &it : x) {
    out << it << " ";
  }
  return out;
}
template <typename T, typename V>
ostream &operator<<(ostream &out, const map<T, V> x) {
  for (auto &it : x) {
    out << "[" << it.first << "]"
        << " = " << it.second << "\n";
  }
  return out;
}
template <typename T>
ostream &operator<<(ostream &out, const vector<T> x) {
  for (int i = 0; i < x.size() - 1; ++i) {
    out << x[i] << " ";
  }
  out << x.back();
  return out;
}
template <typename T>
ostream &operator<<(ostream &out, const vector<vector<T> > x) {
  for (int i = 0; i < x.size() - 1; ++i) {
    out << "[" << i << "]"
        << " = {" << x[i] << "}\n";
  }
  out << "[" << x.size() - 1 << "]"
      << " = {" << x.back() << "}\n";
  return out;
}
const int N = 65;
const int MOD = 1e9 + 7;
const int INF = 1e9;
char a[N][N];
void solve() {
  int n, m;
  cin >> n >> m;
  int cnt = 0;
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < m; ++j) {
      cin >> a[i][j];
      if (a[i][j] == 'A') cnt++;
    }
  }
  if (cnt == 0) {
    cout << "MORTAL";
    return;
  }
  if (cnt == n * m) {
    cout << 0;
    return;
  }
  int ans = 4;
  for (int i = 0; i < n; ++i) {
    bool gd = true;
    for (int j = 0; j < m; ++j) {
      if (a[i][j] != 'A') gd = false;
    }
    if (gd) ans = min(ans, 2);
    if (gd && (i == 0 || i == n - 1)) ans = min(ans, 1);
  }
  for (int i = 0; i < m; ++i) {
    bool gd = true;
    for (int j = 0; j < n; ++j) {
      if (a[j][i] != 'A') gd = false;
    }
    if (gd) ans = min(ans, 2);
    if (gd && (i == 0 || i == m - 1)) ans = min(ans, 1);
  }
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < m; ++j) {
      if (a[i][j] == 'A') {
        if ((i == 0 || i == n - 1) && (j == 0 || j == m - 1)) ans = min(ans, 2);
        if ((i == 0 || i == n - 1) || (j == 0 || j == m - 1)) ans = min(ans, 3);
      }
    }
  }
  cout << ans;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int t;
  cin >> t;
  for (int i = 0; i < t; ++i) {
    solve();
    cout << "\n";
  }
  return 0;
}
