#include <bits/stdc++.h>
using namespace std;
int arr[100][100];
int n, m;
bool bad() {
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      if (arr[i][j]) return 0;
    }
  }
  return 1;
}
bool ans0() {
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      if (arr[i][j] == 0) return 0;
    }
  }
  return 1;
}
bool ans1() {
  bool g1 = 1, g2 = 1, g3 = 1, g4 = 1;
  for (int i = 1; i <= n; i++) {
    g1 &= arr[i][1];
    g2 &= arr[i][m];
  }
  for (int j = 1; j <= m; j++) {
    g3 &= arr[1][j];
    g4 &= arr[n][j];
  }
  return g1 || g2 || g3 || g4;
}
bool ans2() {
  for (int i = 1; i <= n; i++) {
    bool was = 1;
    for (int j = 1; j <= m; j++) {
      was &= arr[i][j];
    }
    if (was) return 1;
  }
  for (int i = 1; i <= m; i++) {
    bool was = 1;
    for (int j = 1; j <= n; j++) {
      was &= arr[j][i];
    }
    if (was) return 1;
  }
  return arr[1][1] || arr[1][m] || arr[n][1] || arr[n][m];
}
bool ans3() {
  for (int i = 1; i <= n; i++)
    if (arr[i][m] || arr[i][1]) return 1;
  for (int i = 1; i <= m; i++)
    if (arr[1][i] || arr[n][i]) return 1;
  return 0;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  int t;
  cin >> t;
  for (int t1 = 1; t1 <= t; t1++) {
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
      for (int j = 1; j <= m; j++) {
        char c;
        cin >> c;
        arr[i][j] = (c == 'P' ? 0 : 1);
      }
    }
    if (bad())
      cout << "MORTAL" << endl;
    else if (ans0())
      cout << 0 << endl;
    else if (ans1())
      cout << 1 << endl;
    else if (ans2())
      cout << 2 << endl;
    else if (ans3())
      cout << 3 << endl;
    else
      cout << 4 << endl;
  }
  return 0;
}
