AcWing 95. 费解的开关
原题链接
中等
作者:
皓首不倦
,
2020-09-15 00:39:57
,
所有人可见
,
阅读 382
'''
枚举第一行可能的状态,根据第一行的状态可以递推出所有后续行的状态,
如果递推到最后最后一行是全1的就找到一种方案,用该方案的操作计数
更新全局的最小计数即可
'''
from copy import deepcopy
n = int(input())
for _ in range(n):
arr = []
while len(arr) != 5:
line = input()
if line == '':
continue
arr.append([ord(ch)-ord('0') for ch in line])
# 翻转i行j列状态
def change(stat, i, j):
if j-1 >= 0:
stat[i][j-1] = 1 - stat[i][j-1]
if j+1 <= 4:
stat[i][j+1] = 1 - stat[i][j+1]
if i+1 <= 4:
stat[i+1][j] = 1 - stat[i+1][j]
stat[i][j] = 1 - stat[i][j]
min_step = 0x7fffffff
for op in range((1<<5)):
cnt = 0
stat = deepcopy(arr)
for j in range(5):
if (1<<j) & op:
change(stat, 0, j)
cnt += 1
flag = True
for i in range(1, 5):
for j in range(5):
if stat[i-1][j] == 0:
change(stat, i, j)
cnt += 1
if cnt >= 7:
flag = False
break
if not flag:
break
if not flag:
continue
if sum(stat[4]) == 5:
min_step = min(min_step, cnt)
ans = min_step if min_step <= 6 else -1
print(ans)