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 T indicating 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 Ncharacters. 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 XXXXXX
http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=5268
#include<iostream> #include<algorithm> #include<string> #include<map> #include<set> #include<cmath> #include<vector> #include<queue> #include<string.h> #include<stdlib.h> #include<cstdio> #define ll long long using namespace std; string x[50]; int n,m; vector<int> y[1601]; int vis[50][50]; int dx[4]={0,0,1,-1}; int dy[4]={1,-1,0,0}; void dfs(int p,int q,int s,char c){ for(int i=0;i<4;++i){ int ii=p+dx[i]; int jj=q+dy[i]; if(ii<0||ii>=n||jj<0||jj>=m) continue; if(x[ii][jj]==c&&vis[ii][jj]==0){ vis[ii][jj]=s; dfs(ii,jj,s,c); } else if(x[ii][jj]!=c&&vis[ii][jj]>0){ y[vis[ii][jj]].push_back(s); y[s].push_back(vis[ii][jj]); } } } int bfs(int p){ int v[1601]={0}; queue<pair<int,int> > q; q.push(make_pair(p,1)); v[p]=1; int max=0; while(!q.empty()){ pair<int,int> fr=q.front(); q.pop(); if(fr.second>max) max=fr.second; for(int i=0;i<y[fr.first].size();++i){ if(v[y[fr.first][i]]==0){ q.push(make_pair(y[fr.first][i],fr.second+1)); v[y[fr.first][i]]=1; } } } return max; } int main(){ int t; scanf("%d",&t); while(t--){ memset(vis,0,sizeof(vis)); cin>>n>>m; for(int i=1;i<=n*m;++i) y[i].clear(); for(int i=0;i<n;++i){ cin>>x[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,x[i][j]); } } } int min=100000000; for(int i=1;i<=cnt;++i){ int p=bfs(i); if(p<min) min=p; } cout<<min-1<<endl; } return 0; }