def print_board(board):
for row in board:
print(" ".join(str(num) for num in row))
def find_empty(board):
for i in range(9):
for j in range(9):
if board[i][j] == 0: # 0 表示空
return i, j
return None
def is_valid(board, num, pos):
row, col = pos
# 检查行
if num in board[row]:
return False
# 检查列
if num in [board[i][col] for i in range(9)]:
return False
# 检查3x3方格
box_x = row // 3
box_y = col // 3
for i in range(box_x*3, box_x*3 + 3):
for j in range(box_y*3, box_y*3 + 3):
if board[i][j] == num:
return False
return True
def solve_sudoku(board):
empty = find_empty(board)
if not empty: # 没有空位置,求解成功
return True
else:
row, col = empty
for num in range(1, 10):
if is_valid(board, num, (row, col)):
board[row][col] = num
if solve_sudoku(board):
return True
board[row][col] = 0 # 重置
return False
# 示例数独棋盘
sudoku_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]
]
if solve_sudoku(sudoku_board):
print_board(sudoku_board)
else:
print("无解")