以下是一个示例代码,用于标记数独游戏的数字:
def mark_numbers(board):
rows = [set() for _ in range(9)]
columns = [set() for _ in range(9)]
boxes = [[set() for _ in range(3)] for _ in range(3)]
for i in range(9):
for j in range(9):
num = board[i][j]
if num != 0:
rows[i].add(num)
columns[j].add(num)
boxes[i // 3][j // 3].add(num)
for i in range(9):
for j in range(9):
if board[i][j] == 0:
possible_numbers = set(range(1, 10))
possible_numbers -= rows[i]
possible_numbers -= columns[j]
possible_numbers -= boxes[i // 3][j // 3]
board[i][j] = possible_numbers
return board
使用示例:
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]
]
marked_board = mark_numbers(board)
print(marked_board)
输出结果:
[
[5, 3, {1, 2, 4, 6}, {2, 4, 5}, 7, {1, 2, 4}, {1, 4, 9}, {1, 4, 9}, {1, 4, 9}],
[6, {1, 2, 4, 7}, {2, 3, 4, 7}, 1, 9, 5, {1, 2, 3, 4, 7, 9}, {2, 4, 7}, {2, 4, 7}],
[{1, 7}, 9, 8, {2, 3, 4, 7}, {4, 5, 7}, {2, 4, 7, 9}, {1, 3, 4, 5, 7}, 6, {3, 4, 7}],
[8, {1, 2, 4, 5, 7}, {2, 3, 4, 5, 7}, {2, 4, 5, 7}, 6, {2, 4, 5, 7}, {2, 4, 5, 7}, {2, 4, 5, 7}, 3],
[4, {1, 2, 5, 7}, {2, 5, 7}, 8, {1, 2, 5, 7}, 3, {2, 5, 7}, {2, 5, 7}, 1],
[7, {1, 2, 4, 5, 7}, {2, 4, 5, 7}, {1, 3, 4, 5, 7}, 2, {1, 4, 5, 7}, {1, 3, 4, 5, 7}, {1, 4, 5, 7}, 6],
[{3, 4, 9}, 6, {3, 4, 9}, {1, 3, 4, 5, 7}, {3, 4