你玩过“拉灯”游戏吗?
25 盏灯排成一个 5×5 的方形。
每一个灯都有一个开关,游戏者可以改变它的状态。
每一步,游戏者可以改变某一个灯的状态。
游戏者改变一个灯的状态会产生连锁反应:和这个灯上下左右相邻的灯也要相应地改变其状态。
我们用数字 1 表示一盏开着的灯,用数字 0 表示关着的灯。
下面这种状态
10111
01101
10111
10000
11011
在改变了最左上角的灯的状态后将变成:
01111
11101
10111
10000
11011
再改变它正中间的灯后状态将变成:
01111
11001
11001
10100
11011
给定一些游戏的初始状态,编写程序判断游戏者是否可能在 6 步以内使所有的灯都变亮。
输入格式
输出格式
数据范围
输入样例:
3
00111
01011
10001
11010
11100
11101
11101
11110
11111
11111
01111
11111
11111
11111
11111
输出样例:
3
2
-1
代码 :
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 6;
char q[N][N], g[N][N];
int dx[5] = {-1, 0, 1, 0, 0}, dy[5] = {0, 1, 0, -1, 0};
void turn(int x, int y)
{
for(int i = 0; i < 5; i ++)
{
int a = x + dx[i], b = y + dy[i];
if(a < 0 || a >= 5 || b < 0 || b >= 5) continue;
q[a][b] ^= 1;
}
}
int main()
{
int n;
cin >> n;
while(n--)
{
for(int i = 0; i < 5; i++) cin >> q[i];
int res = 10;
for(int op = 0; op < 32; op++)
{
memcpy(g, q, sizeof q); //备份
int step = 0;
for(int i = 0; i < 5; i++)
{
if(op >> i & 1)
{
step ++;
turn(0, i);
}
}
for(int i = 0; i < 4; i ++)
{
for(int j = 0; j < 5; j ++)
{
if(q[i][j] == '0')
{
step ++;
turn(i + 1, j);
}
}
}
bool dark = false;
for(int i = 0; i < 5; i ++)
{
if(q[4][i] == '0')
{
dark = true;
break;
}
}
if(!dark) res = min(res, step);
memcpy(q, g, sizeof q);
}
if(res > 6) res = -1;
cout << res << endl;
}
return 0;
}