- Description
翻转棋的棋盘上有64颗棋子,排列成8×8的矩阵。每颗棋子的正反两面分别被涂成白色和黑色。在初始状态下,其中有一些棋子正面朝上(白色),其余的则背面朝上(黑色)。你可以进行如下翻转操作——翻转任意一颗棋子,与此同时与它相邻的上下左右四颗棋子也必须一同翻面。现在给出棋盘的初始状态,请编程计算出至少要进行多少次翻转操作才能让所有的棋子黑色的一面朝上。
- Input
输入的第一行是一个正整数N,代表有N组输入数据。每组数据包含一个8×8的矩阵表示棋盘的初始状态,‘0’代表白色,‘1’代表黑色。两组数据之间以一个空白行分隔。
- Output
对于每一组输入数据,输出一行“Case #: n”。其中‘#’为这一组输出的序号,n为让所有棋子反面向上最少所需的翻转次数。
- Sample Input
2
10111111
00011111
10111111
11111111
11111111
11111111
11111111
11111111
10110001
00011011
10111111
11111111
11111011
11110001
11111111
11110001
- Sample Output
Case 1: 1
Case 2: 4
#include<iostream>
#include<string>
using namespace std;
#define N 10
#define minn(x,y) ((x)<(y)?(x):(y))
char str[N];
int map[N][N],tmap[N][N],ans[N][N];
void Rev(int i,int j)
{
tmap[i][j]=(tmap[i][j]+1)%2;
if(i>0)
tmap[i-1][j]=(tmap[i-1][j]+1)%2;
if(i<8)
tmap[i+1][j]=(tmap[i+1][j]+1)%2;
if(j>0)
tmap[i][j-1]=(tmap[i][j-1]+1)%2;
if(j<8)
tmap[i][j+1]=(tmap[i][j+1]+1)%2;
}
int main()
{
//freopen("in.txt","r",stdin);
int times,i,j,k;
scanf("%d",×);
for(k=1;k<=times;k++)
{
getchar();
int min=256;
for(i=0;i<8;i++)
{
scanf("%s",str);
for(j=0;j<8;j++)
map[i][j]=str[j]-'0';
}
for(int fl=0;fl<256;fl++)
{
int count=0;
memset(ans,0,sizeof(ans));
for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
tmap[i][j]=map[i][j];
}
for(j=0;j<8;j++)
{
if(fl & (1<<j))
{
Rev(0,j);
ans[0][j]=1;
}
}
for(i=1;i<8;i++)
{
for(j=0;j<8;j++)
if(!tmap[i-1][j])
{
Rev(i,j);
ans[i][j]=1;
}
}
for(i=0;i<8;i++)
count+=tmap[7][i];
if(count!=8)
continue;
count=0;
for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
count+=ans[i][j];
}
min=minn(min,count);
}
printf("Case %d: %d\n",k,min);
}
return 0;
}