#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  cin >> t;
  int array[t];
  int arr1[5];
  arr1[0] = 0;
  arr1[1] = 0;
  arr1[2] = 0;
  arr1[3] = 0;
  arr1[4] = 0;
  int ans = 0;
  for (int i = 0; i < t; i++) {
    arr1[0] = 0;
    arr1[1] = 0;
    arr1[2] = 0;
    arr1[3] = 0;
    arr1[4] = 0;
    int m, n, r = 0, p = 0, q = 0;
    cin >> m >> n;
    char arrayy[m][n];
    int newarr1[m], newarr2[n];
    for (int p = 0; p < m; p++) newarr1[p] = 0;
    for (int p = 0; p < n; p++) newarr2[p] = 0;
    for (int j = 0; j < m; j++)
      for (int k = 0; k < n; k++) arrayy[j][k] = 0;
    for (int j = 0; j < m; j++)
      for (int k = 0; k < n; k++) cin >> arrayy[j][k];
    for (int j = 0; j < m; j++)
      for (int k = 0; k < n; k++)
        if (arrayy[j][k] == 'P') newarr1[j]++;
    for (int j = 0; j < n; j++)
      for (int k = 0; k < m; k++)
        if (arrayy[k][j] == 'P') newarr2[j]++;
    if (arrayy[0][0] == 'A' || arrayy[m - 1][0] == 'A' ||
        arrayy[0][n - 1] == 'A' || arrayy[m - 1][n - 1] == 'A')
      arr1[0] = 1;
    for (int j = 1; j < m - 1; j++)
      if (arrayy[j][0] == 'A') arr1[1] = 1;
    for (int j = 1; j < m - 1; j++)
      if (arrayy[j][n - 1] == 'A') arr1[1] = 1;
    for (int j = 1; j < n - 1; j++)
      if (arrayy[0][j] == 'A') arr1[1] = 1;
    for (int j = 1; j < n - 1; j++)
      if (arrayy[m - 1][j] == 'A') arr1[1] = 1;
    for (int j = 1; j < m - 1; j++)
      for (int k = 1; k < n - 1; k++) {
        if (arrayy[j][k] == 'A') arr1[2] = 1;
      }
    for (int z = 1; z < m - 1; z++)
      if (newarr1[z] == 0) {
        arr1[0] = 1;
      }
    for (int z = 1; z < n - 1; z++)
      if (newarr2[z] == 0) {
        arr1[0] = 1;
      }
    if (newarr1[0] == 0 || newarr1[m - 1] == 0 || newarr2[n - 1] == 0 ||
        newarr2[0] == 0)
      arr1[3] = 1;
    for (int j = 0; j < m; j++)
      for (int k = 0; k < n; k++)
        if (arrayy[j][k] == 'A') r++;
    if (r == m * n) arr1[4] = 1;
    if (arr1[4] == 1)
      ans = 0;
    else if (arr1[3] == 1)
      ans = 1;
    else if (arr1[0] == 1)
      ans = 2;
    else if (arr1[1] == 1)
      ans = 3;
    else if (arr1[2] == 1)
      ans = 4;
    else
      ans = 5;
    array[i] = ans;
  }
  for (int l = 0; l < t; l++)
    if (array[l] != 5)
      cout << array[l] << endl;
    else
      cout << "MORTAL" << endl;
}
