defis_valid(board, row, col, num): for i inrange(9): if board[row][i] == num or board[i][col] == num: returnFalse
start_row, start_col = 3 * (row // 3), 3 * (col // 3) for i inrange(3): for j inrange(3): if board[start_row + i][start_col + j] == num: returnFalse
returnTrue
defsolve_sudoku(board): for row inrange(9): for col inrange(9): if board[row][col] == 0: for num inrange(1, 10): if is_valid(board, row, col, num): board[row][col] = num if solve_sudoku(board): returnTrue board[row][col] = 0 returnFalse returnTrue
defprint_board(board): for row in board: print(" ".join(str(num) if num != 0else'.'for num in row))
defparse_input(): board = [] print("请输入数独谜题,每行9个字符,空位用 '-' 表示:") for i inrange(9): whileTrue: line = input(f"第 {i + 1} 行: ") iflen(line) == 9andall(c in'123456789-'for c in line): board.append([int(c) if c != '-'else0for c in line]) break else: print("输入不合法,请重新输入。") return board
if __name__ == "__main__": board = parse_input()
if solve_sudoku(board): print("Sudoku solved successfully:") print_board(board) else: print("No solution exists")