Leo has a grid with N rows and M columns. All cells are painted with either black or white initially.
Two cells A and B are called connected if they share an edge and they are in the same color, or there exists a cell C connected to both A and B.
Leo wants to paint the grid with the same color. He can make it done in multiple steps. At each step Leo can choose a cell and flip the color (from black to white or from white to black) of all cells connected to it. Leo wants to know the minimum number of steps he needs to make all cells in the same color.
There are multiple test cases. The first line of input contains an integer Tindicating the number of test cases. For each test case:
The first line contains two integers N and M (1 <= N, M <= 40). Then N lines follow. Each line contains a string with N characters. Each character is either 'X' (black) or 'O' (white) indicates the initial color of the cells.
For each test case, output the minimum steps needed to make all cells in the same color.
2 2 2 OX OX 3 3 XOX OXO XOX
1 2
For the second sample, one optimal solution is:
Step 1. flip (2, 2)
XOX OOO XOX
Step 2. flip (1, 2)
XXX XXX XXX
题意:给你一个n*m的棋盘,此时上面涂着x(黑色)o(白色)两种颜色。现在你每步可以每次选择一个格来把它和它相邻的相同的颜色的格子涂成相反的颜色,问你最后使得棋盘变为一种颜色的最少步数。
思路:我们的操作其实就是选择一个格子反色然后和这个格子相邻的不同颜色的格子们就都变成了相同的颜色了,然后这些相同颜色的格子其实可以等效成上一个点,然后再反色,和相邻的格子们又变成了相同的颜色,然后再反色........直到所有的格子都变成了相同的颜色。
所以总结一下就是缩点,相同颜色的格子搜索成一个连通块,对于不同颜色的相邻的连通块之间连一条边。
缩完点之后,对于每个连通块进行一次bfs搜索最大的深度。然后答案就是这些最大深度中的最小值啦。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
int n,m;
const int MAXN=50;
char tu[MAXN][MAXN];
int vis[MAXN][MAXN];
int dx[4]={0,0,-1,1};
int dy[4]={1,-1,0,0};
vector<int>G[1620];
void dfs(int x,int y,int num,char c)
{
for(int i=0;i<4;++i)
{
int nx=x+dx[i];
int ny=y+dy[i];
if(nx<0||nx>=n||ny<0||ny>=m)continue;
if(!vis[nx][ny]&&tu[nx][ny]==c)
{
vis[nx][ny]=num;
dfs(nx,ny,num,c);
}
else if(tu[nx][ny]!=c&&vis[nx][ny])
{
int v=vis[nx][ny];
G[v].push_back(num);
G[num].push_back(v);
}
}
}
int bfs(int s)
{
bool vs[1620]={0};
queue<pair<int,int> >q;
q.push(make_pair(s,0));
vs[s]=1;
int MAX=0;
while(!q.empty())
{
pair<int,int>k=q.front();
q.pop();
MAX=max(MAX,k.second);
int u=k.first;
for(int i=0,l=G[u].size();i<l;++i)
{
int v=G[u][i];
if(!vs[v])
{
vs[v]=1;
q.push(make_pair(v,k.second+1));
}
}
}
return MAX;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
memset(vis,0,sizeof(vis));
for(int i=0;i<n*m;++i)G[i].clear();
scanf("%d%d",&n,&m);
for(int i=0;i<n;++i)scanf("%s",tu[i]);
int cnt=0;
for(int i=0;i<n;++i)
for(int j=0;j<m;++j)
{
if(!vis[i][j])
{
vis[i][j]=++cnt;
dfs(i,j,cnt,tu[i][j]);
}
}
int ans=1e9;
for(int i=1;i<=cnt;++i)
{
ans=min(ans,bfs(i));
}
printf("%d\n",ans);
}
return 0;
}