#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
struct node {
int x, y, t;
bool operator<(const node& a) const {
return t > a.t;
}
};
int n, m;
int dx[4] = { 0,0,-1,1 }, dy[4] = { 1,-1,0,0 };
char map[1005][1005];
bool vis[1005][1005];
int dis[1005][1005];
inline int bfs() {
priority_queue<node> q;
q.push(node{1,1,0});
vis[1][1] = true;
memset(dis,0x3f3f3f3f,sizeof(dis));
dis[1][1]=0;
while(!q.empty()) {
int nx = q.top().x, ny = q.top().y, nt = q.top().t;
q.pop();
for (int i = 0; i < 4; i++) {
int tx = nx + dx[i], ty = ny + dy[i];
if (tx >= 1 && tx <= n && ty >= 1 && ty <= m ) {
if (map[tx][ty] != map[nx][ny] && dis[tx][ty]>dis[nx][ny]+1)
dis[tx][ty]=dis[nx][ny]+1;
else
if(map[tx][ty] == map[nx][ny] && dis[tx][ty]>dis[nx][ny])
dis[tx][ty]=dis[nx][ny];
if(!vis[tx][ty]) {
q.push(node{tx,ty,dis[tx][ty]});
vis[tx][ty] = true;
}
}
}
}
return dis[n][m];
}
int main() {
int T;
scanf("%d",&T);
while (T--) {
scanf("%d%d",&n,&m);
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++)
cin>>map[i][j];
memset(vis,false,sizeof(vis));
cout<<bfs()<<endl;
}
return 0;
}
实在找不出错误了,就是WA...