#include <bits/stdc++.h>
// #include <atcoder/all>
using namespace std;
#define int long long
#define all(x) (x).begin(), (x).end()
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<pair<int, int>> vpi;
typedef pair<int, int> pi;
#define f first
#define s second
#define pb push_back
#define endl "\n"
#define yes cout << "YES" << endl
#define no cout << "NO" << endl
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
const int mod1 = 1e9 + 7, mod2 = 998244353, INF = 2e18, N = 2e5 + 5, L = 19;
int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
// -----------------------------------------------------------------------------
int n, m, depth[N][N];
string snow[N];
bool inside(int x, int y)
{
return (x >= 0 && x < n && y >= 0 && y < m && snow[x][y] != '.');
}
void solve()
{
cin >> n >> m;
for (int i = 0; i < n; i++)
{
cin >> snow[i];
fill(depth[i], depth[i] + m, 0);
}
int ans = 0;
deque<pi> dq;
dq.push_back({0, 0});
depth[0][0] = 1;
while (!dq.empty())
{
auto [x, y] = dq.front();
dq.pop_front();
ans = max(ans, depth[x][y]);
for (int i = 0; i < 4; i++)
{
int newx = x + dx[i], newy = y + dy[i];
if (inside(newx, newy) && depth[newx][newy] == 0)
{
if (snow[x][y] == snow[newx][newy])
{
depth[newx][newy] = depth[x][y];
dq.push_front({newx, newy});
}
else
{
depth[newx][newy] = depth[x][y] + 1;
dq.push_back({newx, newy});
}
}
}
}
cout << ans << endl;
}
signed main()
{
// __START__;
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t = 1;
cin >> t;
while (t--)
{
solve();
}
// __END__;
return 0;
}