https://vjudge.net/contest/294469#problem/F
#pragma comment (linker,"/STACK:1024000000,1024000000")
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#include<cstdlib>
#include<cmath>
#include<stack>
#include<map>
#include<vector>
#include<algorithm>
using namespace std;
#define ll long long
#define lb long double
#define INF 0x3f3f3f3f
const int maxn = 45;
const ll mod = 1e9 + 7;
int t, n, m, cnt, num, mini = INF;
char s[maxn][maxn];
int head[maxn*maxn], col[maxn][maxn];
bool judge[maxn*maxn][maxn*maxn], vis[maxn*maxn];
int dir[4][2] = {1, 0, 0, -1, -1, 0, 0, 1};
struct node{
int to;
int next;
}edge[maxn*maxn*maxn*maxn];
struct nod{
int u;
int d;
};
void add(int u, int v){
edge[cnt].to = v;
edge[cnt].next = head[u];
head[u] = cnt ++;
}
void init(){
scanf("%d %d", &n, &m);
getchar();
for(int i = 1 ; i <= n ; ++ i){
scanf("%s", s[i] + 1);
}
cnt = 0;
num = 0;
mini = INF;
//memset(edge, 0, sizeof(edge));
memset(judge, 0, sizeof(judge));
memset(col, -1, sizeof(col));
memset(head, -1, sizeof(head));
}
void dfs(int x, int y, int c){
for(int i = 0 ; i < 4 ; ++ i){
int tx = x + dir[i][0];
int ty = y + dir[i][1];
if(tx < 1 || tx > n || ty < 1 || ty > m) continue;
if(s[x][y] == s[tx][ty]){
if(col[tx][ty] == -1){
col[tx][ty] = c;
dfs(tx, ty, c);
}
}
else{
if(col[tx][ty] != -1){
int u = col[x][y], v = col[tx][ty];
if(!judge[u][v] && u != v){
add(u, v); add(v, u);
judge[u][v] = 1; judge[v][u] = 1;
}
}
}
}
}
int bfs(int s){
int maxi = 0;
memset(vis, 0, sizeof(vis));
queue<nod> que;
vis[s] = 1;
nod temp;
temp.u = s; temp.d = 0;
que.push(temp);
while(!que.empty()){
nod cur = que.front();
que.pop();
if(cur.d > mini) return INF;
for(int i = head[cur.u] ; i != -1 ; i = edge[i].next){
int tt = edge[i].to;
if(tt == cur.u) continue;
if(!vis[tt]){
vis[tt] = 1;
nod temp;
temp.u = tt; temp.d = cur.d + 1;
que.push(temp);
maxi = max(maxi, cur.d + 1);
}
}
}
return maxi;
}
int main()
{
scanf("%d", &t);
while(t--){
init();
for(int i = 1 ; i <= n ; ++ i){
for(int j = 1 ; j <= m ; ++ j){
if(col[i][j] == -1){
col[i][j] = ++ num;
dfs(i, j, num);
}
}
}
for(int i = 1 ; i <= num ; ++ i){
mini = min(mini, bfs(i));
}
printf("%d\n", mini);
}
return 0;
}