题意:
给定一个5X5的灯阵,1表示灯亮着,0表示灯灭了,每次操作可以选择一盏灯并改变他的状态和他周围灯的状态(周围:上下左右)然后问你最少多少次能够使所有灯都变成亮着的状态,如果次数大于6则输出-1,否则输出最少的操作数。
思路:
我们可以从上往下不断的确定状态,使得除最后一行之外所有的灯变亮,最后再判断一下最后一行的灯是否都亮着,如果都亮着证明该方案可行,将答案取min更新。先来看第一行,总共有25种操作方案,所以我们全部枚举暴力不就行了吗(雾 。继续判断后面的行如果有熄灭的那么就改下一行的来达到目标。
AC代码
#include<iostream>
using namespace std;
const int INF = 0x3f3f3f3f;
typedef long long ll;
int dirx[5] = {0,0,0,-1,1};
int diry[5] = {0,-1,1,0,0};
string mp[11];
bool in(int x,int y) {
return x>=0&&x<5&&y>=0&&y<5;
}
void turn(int x,int y) {
for(int i=0;i<5;i++) {
int tx = x+dirx[i];
int ty = y+diry[i];
if(!in(tx,ty)) continue;
mp[tx][ty] ^= 1;
}
}
void solve() {
int res = INF;
for(int i=0;i<1<<5;i++) {
int cnt = 0;
string tmp[11];
for(int j=0;j<5;j++) tmp[j] = mp[j];
for(int j=0;j<5;j++) {
if(i>>j&1) {
turn(0,j);
cnt++;
}
}
for(int j=0;j<4;j++) {
for(int k = 0;k<5;k++) {
if(mp[j][k] == '0') {
turn(j+1,k);
cnt++;
}
}
}
bool flag = true;
for(int j=0;j<5;j++) {
if(mp[4][j] == '0') {
flag = false;
}
}
if(flag) res = min(res,cnt);
for(int j=0;j<5;j++) mp[j] = tmp[j];
}if(res<=6) cout<<res<<endl;
else cout<<"-1\n";
}
int main()
{
int t;
cin>>t;
while(t--) {
for(int i=0;i<5;i++) cin>>mp[i];
solve();
}
}