# sudoku here
# 原题
line1 = [0, 0, 8, 0, 0, 0, 2, 0, 0]
line2 = [0, 3, 0, 8, 0, 2, 0, 6, 0]
line3 = [7, 0, 0, 0, 9, 0, 0, 0, 5]
line4 = [0, 5, 0, 0, 0, 0, 0, 1, 0]
line5 = [0, 0, 4, 0, 0, 0, 6, 0, 0]
line6 = [0, 2, 0, 0, 0, 0, 0, 7, 0]
line7 = [4, 0, 0, 0, 8, 0, 0, 0, 6]
line8 = [0, 7, 0, 1, 0, 3, 0, 9, 0]
line9 = [0, 0, 1, 0, 0, 0, 8, 0, 0]
# solution here
def which_block(where): # 获取这个数所在的宫有哪些数
line = where[1] + 1
exec(f'row = {where[0] + 1}', globals())
if line < 4 and row < 4:
return set(line1[:4] + line2[:4] + line3[:4])
elif 7 > line > 3 and row < 4:
return set(line4[:4] + line5[:4] + line6[:4])
elif line > 6 and row < 4:
return set(line7[:4] + line8[:4] + line9[:4])
if line < 4 and 3 < row < 7:
return set(line1[:4] + line2[:4] + line3[:4])
elif 7 > line > 3 and 3 < row < 7:
return set(line4[:4] + line5[:4] + line6[:4])
elif line > 6 and 3 < row < 7:
return set(line7[:4] + line8[:4] + line9[:4])
if line < 4 and 6 < row:
return set(line1[:4] + line2[:4] + line3[:4])
elif 7 > line > 3 and 6 < row:
return set(line4[:4] + line5[:4] + line6[:4])
elif line > 6 and 6 < row:
return set(line7[:4] + line8[:4] + line9[:4])
def solve_one(where): # 求解一个数
exec(f'number = line{where[1] + 1}[{where[0]}]', globals()) # 求这个数是什么
exec(f'line = line{where[1] + 1}', globals())
exec(f'row = {where[0]}', globals())
row_numbers = []
for i in range(9):
exec(f'row_numbers.append(line{i + 1}[row])') # 一列都有什么数
numbers = set(range(1, 10))
if number == 0: # 只有这个数未知才判断
numbers = numbers - set(line) # 一行去除相同数
numbers = numbers - set(row_numbers) # 一列去除相同数
numbers = numbers - which_block(where) # 一宫去除相同数
if len(numbers) == 1: # 如果有唯一数就返回它
exec(f'line{where[1] + 1}[{where[0]}] = list(numbers)[0]') # 更新数独
return list(numbers)[0]
else:
return # 求不出就退出等待下次
else:
return
temp = 0
while 0 in line1 + line2 + line3 + line4 + line5 + line6 + line7 + line8 + line9: # 如果还有零就继续循环
for ii in range(9):
for jj in range(9):
result = solve_one((ii, jj))
print(line1, line2, line3, line4, line5, line6, line7, line8, line9, '\n', sep='\n')
temp += 1 # 控制循环次数
if temp >= 100:
break
# 100 steps here
# while循环一百次结果
[9, 4, 8, 0, 0, 0, 2, 5, 0]
[0, 3, 5, 8, 0, 2, 0, 6, 0]
[7, 1, 6, 2, 9, 0, 0, 4, 5]
[0, 5, 0, 0, 6, 7, 0, 1, 9]
[1, 8, 4, 0, 7, 9, 6, 3, 0]
[3, 2, 0, 0, 0, 6, 9, 7, 0]
[4, 9, 0, 0, 8, 5, 3, 2, 6]
[0, 7, 2, 1, 0, 3, 5, 9, 8]
[5, 6, 1, 0, 0, 0, 8, 0, 3]
# question
# 执行到20次左右时结果就不会再变了
# 手工做了一下, 发现答案不符
# 速度每次循环(1 step)耗时0.0149秒