#include <bits/stdc++.h>
using namespace std;
char maze[100][100];
int main() {
  int T;
  cin >> T;
  while (T--) {
    int n, m;
    cin >> n >> m;
    for (int i = 0; i < n; ++i) {
      cin >> maze[i];
    }
    bool flag = true;
    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < m; ++j) {
        if (maze[i][j] == 'A') flag = false;
      }
    }
    int ct = 0;
    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < m; ++j) {
        if (maze[i][j] == 'A') ++ct;
      }
    }
    if (ct == n * m) {
      cout << 0 << endl;
      continue;
    }
    if (flag)
      cout << "MORTAL" << endl;
    else {
      int CNT = 4;
      if (maze[0][0] == 'A' || maze[n - 1][0] == 'A' || maze[0][m - 1] == 'A' ||
          maze[n - 1][m - 1] == 'A')
        CNT = 2;
      bool flag = true;
      for (int j = 0; j < m; ++j) {
        if (maze[0][j] != 'A') flag = false;
      }
      if (flag)
        CNT = 1;
      else {
        flag = true;
        for (int j = 0; j < m; ++j) {
          if (maze[n - 1][j] != 'A') flag = false;
        }
        if (flag) CNT = 1;
      }
      flag = true;
      for (int j = 0; j < n; ++j) {
        if (maze[j][0] != 'A') flag = false;
      }
      if (flag) CNT = 1;
      flag = true;
      for (int i = 0; i < m; ++i) {
        if (maze[0][i] == 'A' || maze[n - 1][i] == 'A') CNT = min(CNT, 3);
      }
      for (int i = 0; i < n; ++i) {
        if (maze[i][0] == 'A' || maze[i][m - 1] == 'A') CNT = min(CNT, 3);
      }
      for (int j = 0; j < n; ++j) {
        if (maze[j][m - 1] != 'A') flag = false;
      }
      if (flag) CNT = 1;
      for (int i = 0; i < n; ++i) {
        flag = true;
        for (int j = 0; j < m; ++j) {
          if (maze[i][j] != 'A') flag = false;
        }
        if (flag) CNT = min(CNT, 2);
      }
      for (int i = 0; i < m; ++i) {
        flag = true;
        for (int j = 0; j < n; ++j) {
          if (maze[j][i] != 'A') flag = false;
        }
        if (flag) CNT = min(CNT, 2);
      }
      cout << CNT << endl;
    }
  }
  return 0;
}
