Python 数独游戏:代码实现及解析
以下是用 Python 编写的 9x9 数独游戏代码:
def print_board(board):
for i in range(len(board)):
if i % 3 == 0 and i != 0:
print('- - - - - - - - - - - - - -')
for j in range(len(board[0])):
if j % 3 == 0 and j != 0:
print(' | ', end='')
if j == 8:
print(board[i][j])
else:
print(str(board[i][j]) + ' ', end='')
def find_empty(board):
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 0:
return (i, j)
return None
def valid(board, num, pos):
# 检查行
for i in range(len(board[0])):
if board[pos[0]][i] == num and pos[1] != i:
return False
# 检查列
for i in range(len(board)):
if board[i][pos[1]] == num and pos[0] != i:
return False
# 检查九宫格
box_x = pos[1] // 3
box_y = pos[0] // 3
for i in range(box_y * 3, box_y * 3 + 3):
for j in range(box_x * 3, box_x * 3 + 3):
if board[i][j] == num and (i, j) != pos:
return False
return True
def solve(board):
find = find_empty(board)
if not find:
return True
else:
row, col = find
for i in range(1, 10):
if valid(board, i, (row, col)):
board[row][col] = i
if solve(board):
return True
board[row][col] = 0
return False
# 数独游戏的初始数独板
board = [
[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
[0, 0, 0, 0, 8, 0, 0, 7, 9]
]
print('初始数独板:')
print_board(board)
solve(board)
print('\n解决数独板:')
print_board(board)
运行上述代码,将会打印出初始的数独板和解决后的数独板。
代码解析:
print_board(board)函数用于打印数独板,格式化输出,方便用户查看。find_empty(board)函数用于查找数独板上的第一个空位置 (值为 0 的位置)。valid(board, num, pos)函数用于判断将数字num放置在位置pos上是否合法,需要检查该数字在同一行、同一列和同一九宫格内是否重复出现。solve(board)函数是数独求解的核心函数,使用递归回溯算法,尝试将数字 1 到 9 依次填入空位置,判断填入后是否合法,并递归调用自身尝试填入下一个空位置。
通过以上代码,您可以轻松地使用 Python 编写一个数独游戏,并理解数独游戏求解的算法原理。
希望这篇文章对您有所帮助!
原文地址: https://www.cveoy.top/t/topic/o35i 著作权归作者所有。请勿转载和采集!