题意
能够上下左右相通的并且颜色相同的块为一个整体,就是所谓的联通块。然后每次对联通块进行反转颜色操作,最后要求最小的步数使得图中所有的颜色相同。
思路
- 将所有能够相通的相同颜色进行缩点,形成联通块
- 然后能够上下左右连通的联通块进行建边
- 最后枚举所有的联通块,进行 b f s bfs bfs 标记操作,将所有的答案取最小值,就是最终答案
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
template <typename T>
inline void rd(T& x)
{
ll tmp = 1; char c = getchar(); x = 0;
while (c > '9' || c < '0') {
if (c == '-')tmp = -1; c = getchar(); }
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0'; c = getchar(); }
x *= tmp;
}
const int inf = 0x3f3f3f3f;
const int mod = 7;
const int N = 2e4 + 10;
const int M = 1e7 + 10;
const double eps = 1e-8;
int n, m;
char mp[55][55];
bool vis[55][55];
int num[55][55];
int dir[][2] = {
1,0,-1,0,0,1,0,-1 }, cnt;
void bfs(int x,int y) {
queue<pii>que;
que.push({
x,y });
stack<pii>stk;
while (!que.empty()) {
pii p = que.front(); que.pop();
stk.push(p);
if (vis[p.first][p.second]) continue;
vis[p.first][p.second] = 1;
for (int i = 0; i < 4; ++i) {
int xx = p.first + dir[i][0], yy = p.second + dir[i][1];
if (xx <= 0 || xx > n || yy <= 0 || yy > m || vis[xx][yy] || mp[xx][yy] != mp[p.first][p.second]) continue;
que.push({
xx,yy });
}
}
++cnt;
while (!stk.empty()) {
pii p = stk.top(); stk.pop();
num[p.first][p.second] = cnt;
}
}
int head[N], cntE;
struct edge {
int next, to;
}e[M];
void add(int u, int v) {
e[cntE].to = v;
e[cntE].next = head[u];
head[u] = cntE++;
}
bool mark[N];
int bfs(int x) {
queue<pii>que;
que.push({
x,1 });
int ans = 0;
while (!que.empty()) {
pii p = que.front(); que.pop();
int u = p.first;
if (mark[u]) continue;
mark[u] = true;
ans = max(ans, p.second);
for (int i = head[u]; ~i; i = e[i].next) {
int v = e[i].to;
if (mark[v]) continue;
que.push({
v,p.second + 1 });
}
}
return ans-1;
}
int solve() {
memset(vis, false, sizeof vis); cnt = 0;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
if (vis[i][j]) continue;
bfs(i, j);
}
}
memset(head, -1, sizeof head); cntE = 0;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
for (int k = 0; k < 4; ++k) {
int x = i + dir[k][0], y = j + dir[k][1];
if (x <= 0 || x > n || y <= 0 || y > m) continue;
if (num[x][y] != num[i][j]) add(num[i][j], num[x][y]);
}
}
}
int minn = inf;
for (int i = 1; i <= cnt; ++i) {
for (int j = 1; j <= cnt; ++j) mark[j] = false;
minn = min(minn, bfs(i));
}
return minn;
}
int main() {
ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
// FILE* _INPUT = freopen("input.txt", "r", stdin);
// FILE* _OUTPUT = freopen("output.txt", "w", stdout);
int T; rd(T);
while (T--) {
rd(n), rd(m);
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
scanf(" %c", &mp[i][j]);
}
}
printf("%d\n", solve());
}
return 0;
}