#include <bits/stdc++.h>
using namespace std;
long long zero = 0;
long long one = 1;
long long gcd(long long a, long long b) {
  if (b == 0) return a;
  return gcd(b, a % b);
}
long long lcm(long long a, long long b) { return (a / gcd(a, b) * b); }
long long expo(long long x, long long y) {
  long long res = 1;
  x = x % 1000000007;
  while (y > 0) {
    if (y & 1) res = (1ll * res * x) % 1000000007;
    y = y >> 1;
    x = (1ll * x * x) % 1000000007;
  }
  return res;
}
long long ncr(long long n, long long r) {
  long long res = 1;
  if (r > n - r) r = n - r;
  for (long long i = 0; i < r; i++) {
    res *= n - i;
    res /= i + 1;
  }
  return res;
}
long long max(long long a, long long b) { return (a > b) ? a : b; }
bool prime(long long n) {
  long long i;
  for (i = 2; i <= sqrt(n); i++) {
    if (n % i == 0) return false;
  }
  return true;
}
bool sortbysec(const pair<long long, long long> &a,
               const pair<long long, long long> &b) {
  return (a.second <= b.second);
}
int solve(int r, int c, vector<string> v) {
  vector<int> row(r, 0), col(c, 0);
  int total = 0;
  for (long long i = 0; i < (long long)r; i++) {
    for (long long j = 0; j < (long long)c; j++) {
      if (v[i][j] == 'A') {
        row[i]++;
        col[j]++;
        total++;
      }
    }
  }
  if (total == r * c) return 0;
  if (total == 0) return -1;
  if (row[0] == c || row.back() == c || col[0] == r || col.back() == r)
    return 1;
  if (v[0][0] == 'A' || v[0].back() == 'A' || v.back()[0] == 'A' ||
      v.back().back() == 'A')
    return 2;
  if (*max_element(row.begin(), row.end()) == c ||
      *max_element(col.begin(), col.end()) == r)
    return 2;
  if (row[0] || row.back() || col[0] || col.back()) return 3;
  return 4;
}
signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  int r, c;
  int res;
  long long t;
  cin >> t;
  while (t--) {
    cin >> r >> c;
    vector<string> v(r);
    for (long long i = 0; i < (long long)r; i++) cin >> v[i];
    res = solve(r, c, v);
    res == -1 ? cout << "MORTAL" << endl : cout << res << endl;
  }
}
