#include <bits/stdc++.h>
using namespace std;
const int inf = (int)1e9;
const int mod = (int)1e9 + 7;
bool check_00(vector<vector<int> > v) {
  for (auto x : v) {
    for (int y : x) {
      if (y == 0) {
        return 0;
      }
    }
  }
  return 1;
}
bool check_0(vector<vector<int> > v) {
  bool correct = 1;
  for (int i = 0; i < (int)v.size(); ++i) {
    if (v[i][0] == 0) {
      correct = 0;
      break;
    }
  }
  if (correct) {
    return 1;
  }
  correct = 1;
  for (int j = 0; j < (int)v[0].size(); ++j) {
    if (v[0][j] == 0) {
      correct = 0;
      break;
    }
  }
  if (correct) {
    return 1;
  }
  correct = 1;
  for (int j = 0; j < (int)v[0].size(); ++j) {
    if (v.back()[j] == 0) {
      correct = 0;
      break;
    }
  }
  if (correct) {
    return 1;
  }
  correct = 1;
  for (int i = 0; i < (int)v.size(); ++i) {
    if (v[i].back() == 0) {
      correct = 0;
      break;
    }
  }
  return correct;
}
bool check_1(vector<vector<int> > v) {
  return v[0][0] == 1 || v[0].back() == 1 || v.back()[0] == 1 ||
         v.back().back();
}
bool check_2(vector<vector<int> > v) {
  for (int i = 0; i < (int)v.size(); ++i) {
    bool correct = 1;
    for (int j = 0; j < (int)v[0].size(); ++j) {
      if (v[i][j] == 0) {
        correct = 0;
        break;
      }
    }
    if (correct) {
      return 1;
    }
  }
  for (int j = 0; j < (int)v[0].size(); ++j) {
    bool correct = 1;
    for (int i = 0; i < (int)v.size(); ++i) {
      if (v[i][j] == 0) {
        correct = 0;
        break;
      }
    }
    if (correct) {
      return 1;
    }
  }
  return 0;
}
bool check_3(vector<vector<int> > v) {
  for (int i = 0; i < (int)v.size(); ++i) {
    if (v[i][0] == 1 || v[i].back() == 1) {
      return 1;
    }
  }
  for (int j = 0; j < (int)v[0].size(); ++j) {
    if (v[0][j] == 1 || v.back()[j] == 1) {
      return 1;
    }
  }
  return 0;
}
bool check_4(vector<vector<int> > v) {
  for (int i = 1; i < (int)v.size() - 1; ++i) {
    for (int j = 1; j < (int)v[0].size() - 1; ++j) {
      if (v[i][j] == 1) {
        return 1;
      }
    }
  }
  return 0;
}
int main() {
  int q;
  scanf("%d", &q);
  while (q--) {
    int n, m;
    scanf("%d%d", &n, &m);
    vector<vector<int> > v(n, vector<int>(m, 0));
    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < m; ++j) {
        char c;
        scanf(" %c", &c);
        if (c == 'A') {
          v[i][j] = 1;
        }
      }
    }
    if (check_00(v)) {
      printf("0\n");
      continue;
    }
    if (check_0(v)) {
      printf("1\n");
      continue;
    }
    if (check_1(v)) {
      printf("2\n");
      continue;
    }
    if (check_2(v)) {
      printf("2\n");
      continue;
    }
    if (check_3(v)) {
      printf("3\n");
      continue;
    }
    if (check_4(v)) {
      printf("4\n");
      continue;
    }
    printf("MORTAL\n");
  }
  return 0;
}
