#include <bits/stdc++.h>
using namespace std;
int t;
int ans[20001];
int main() {
  cin >> t;
  for (int c = 1; c <= t; c++) {
    int u, v;
    cin >> u >> v;
    bool mat[61][61];
    for (int i = 1; i <= u; i++) {
      string s;
      cin >> s;
      for (int j = 1; j <= s.size(); j++) {
        if (s[j - 1] == 'A')
          mat[i][j] = 1;
        else
          mat[i][j] = 0;
      }
    }
    bool p = 1;
    for (int i = 1; i <= u; i++) {
      for (int j = 1; j <= v; j++) {
        p = p & mat[i][j];
      }
    }
    if (p) {
      ans[c] = 0;
      continue;
    }
    p = 0;
    for (int i = 1; i <= u; i++) {
      for (int j = 1; j <= v; j++) {
        p = p | mat[i][j];
      }
    }
    if (!p) {
      ans[c] = -1;
      continue;
    }
    bool c1 = 1, c2 = 1;
    for (int i = 1; i <= u; i++) {
      c1 = c1 & mat[i][1];
      c2 = c2 & mat[i][v];
    }
    bool r1 = 1, r2 = 1;
    for (int i = 1; i <= v; i++) {
      r1 = r1 & mat[1][i];
      r2 = r2 & mat[u][i];
    }
    if (c1 | c2 | r1 | r2) {
      ans[c] = 1;
      continue;
    }
    if (mat[u][v] | mat[1][1] | mat[1][v] | mat[u][1]) {
      ans[c] = 2;
      continue;
    }
    bool k = 0;
    for (int i = 2; i <= u - 1; i++) {
      p = 1;
      for (int j = 1; j <= v; j++) {
        p = p & mat[i][j];
      }
      if (p) {
        k = 1;
        break;
      }
    }
    if (k) {
      ans[c] = 2;
      continue;
    }
    k = 0;
    for (int i = 2; i <= v - 1; i++) {
      p = 1;
      for (int j = 1; j <= u; j++) {
        p = p & mat[j][i];
      }
      if (p) {
        k = 1;
        break;
      }
    }
    if (k) {
      ans[c] = 2;
      continue;
    }
    bool l1 = 0, l2 = 0, l3 = 0, l4 = 0;
    for (int i = 1; i < v; i++) {
      l1 = l1 | mat[1][i];
      l2 = l2 | mat[u][i + 1];
    }
    for (int i = 1; i < u; i++) {
      l3 = l3 | mat[i][v];
      l4 = l4 | mat[i + 1][1];
    }
    if (l1 | l2 | l3 | l4)
      ans[c] = 3;
    else
      ans[c] = 4;
  }
  for (int i = 1; i <= t; i++) {
    if (ans[i] == -1)
      cout << "MORTAL" << endl;
    else
      cout << ans[i] << endl;
  }
  return 0;
}
