python回溯算法解数独
记录使用回溯算法解析数独# 数独计算
import copy
def sudoku_analyze(board):
def isValid(board, r, c, n):
for i in range(9):
if board == n:
return False
if board == n:
return False
if board[int(r / 3) * 3 + int(i / 3)][int(c / 3) * 3 + i % 3] == n:
return False
return True
def backtrack(board, i, j):
m, n = 9, 9
if j == n:
return backtrack(board, i + 1, 0)
if i == m:
return True
if board != 0:
return backtrack(board, i, j + 1)
for ch in range(1, 10):
if not isValid(board, i, j, ch):
continue
board = ch
if backtrack(board, i, j + 1):
return True
board = 0
return False
backtrack(board, 0, 0)
# array = [[-1] * 9 for _ in range(9)]# 输入的数独矩阵
array = [
[0, 0, 0, 6, 0, 4, 7, 0, 0],
[7, 0, 6, 0, 0, 0, 0, 0, 9],
[0, 0, 0, 0, 0, 5, 0, 8, 0],
[0, 7, 0, 0, 2, 0, 0, 9, 3],
[8, 0, 0, 0, 0, 0, 0, 0, 5],
[4, 3, 0, 0, 1, 0, 0, 7, 0],
[0, 5, 0, 2, 0, 0, 0, 0, 0],
[3, 0, 0, 0, 0, 0, 2, 0, 8],
[0, 0, 2, 3, 0, 1, 0, 0, 0],
]
array_copy = copy.deepcopy(array)
sudoku_analyze(array_copy)
for i in range(9):
print("\033, end='')# 白色
if i % 3 == 0:
# print('=' * line)
print('++===+===+===++===+===+===++===+===+===++')
else:
print('++---+---+---++---+---+---++---+---+---++')
for j in range(9):
print("\033, end='')# 白色
if j % 3 == 0:
print('||', end='')
else:
print('|', end='')
print(' ', end='')
if array == array_copy:
print("\033, end='')# 红色
else:
print("\033, end='')# 灰色
print(array_copy, end='')
print(' ', end='')
print("\033, end='')# 白色
print('||', end='')
print()
print('=' * line) 支持一下楼主 感谢分享 支持 有成品效果吗 {:1_927:} 学习了,支持你哦。
页:
[1]