可以用以下代码来生成一个数独:
import random
def generate_sudoku():
# 创建一个9x9的空白数独
sudoku = [[0 for _ in range(9)] for _ in range(9)]
# 填充第一行
for i in range(9):
sudoku[0][i] = (i + 1) % 9 + 1
# 使用洗牌算法生成数独
for i in range(1, 9):
for j in range(9):
sudoku[i][j] = sudoku[0][(j + i * 3) % 9]
# 随机打乱行
random.shuffle(sudoku)
# 随机打乱列
for i in range(9):
col1 = random.randint(0, 2)
col2 = random.randint(0, 2)
for j in range(9):
sudoku[j][i] = sudoku[j][(i + 3 * col1) % 9]
sudoku[j][(i + 3 * col1) % 9] = sudoku[j][(i + 3 * col2) % 9]
sudoku[j][(i + 3 * col2) % 9] = sudoku[j][i]
return sudoku
def print_sudoku(sudoku):
for i in range(9):
for j in range(9):
print(sudoku[i][j], end=" ")
print()
sudoku = generate_sudoku()
print_sudoku(sudoku)
运行此代码将生成并打印一个数独。