題目鏈接
參考了算法競賽進階指南和大佬博客
枚舉第一行的點擊方法,採用位運算的方式,枚舉0~31,若第k位爲1,就點擊01矩陣第一行第k+1列的數字
#include<cstdio>
#include<algorithm>
using namespace std;
#define _rep(i,a,b) for(int i=(a);i<=(b);i++)
#define _for(i,a,b) for(int i=(a);i<(b);i++)
#define INF 0x3f3f3f3f3f
int n;
char s[6];
int mp[6][6];
int tmp[6][6];
inline void work(int x,int y)
{
tmp[x][y]=tmp[x][y]^1;
if(x-1)tmp[x-1][y]=tmp[x-1][y]^1;
if(x+1<=5)tmp[x+1][y]=tmp[x+1][y]^1;
if(y-1)tmp[x][y-1]=tmp[x][y-1]^1;
if(y+1<=5)tmp[x][y+1]=tmp[x][y+1]^1;
}
int main()
{
//freopen("in.txt","r",stdin);
scanf("%d",&n);
while(n--)
{
int ans=INF;
_rep(i,1,5)
{
scanf("%s",s+1);
_rep(j,1,5)mp[i][j]=(s[j]-'0')^1;
}
_for(s,0,31)
{
int step=0;
_rep(i,1,5)_rep(j,1,5)tmp[i][j]=mp[i][j];
int S=s;
int pos=1;
while(S)//之前把這裏寫錯了
{
if(S&1)work(1,pos),step++;
pos++;S>>=1;
}
_rep(i,2,5)_rep(j,1,5)if(tmp[i-1][j])work(i,j),step++;
bool legal=1;
_rep(j,1,5)if(tmp[5][j])legal=0;
if(legal)ans=min(ans,step);
}
if(ans>6)puts("-1");
else printf("%d\n",ans);
}
return 0;
}