以下是九宫格数独问题的回溯法解决方案代码:

def solve_sudoku(board):
    """
    Solve the Sudoku puzzle using backtracking.

    :param board: 9x9 matrix representing the Sudoku puzzle
    :return: True if the puzzle is solvable, False otherwise
    """
    # Find an empty cell
    empty_cell = find_empty_cell(board)

    # If there is no empty cell, the puzzle is solved
    if not empty_cell:
        return True

    # Try each possible value for the empty cell
    for val in range(1, 10):
        if is_valid_move(board, empty_cell[0], empty_cell[1], val):
            # If the move is valid, fill the empty cell with the value
            board[empty_cell[0]][empty_cell[1]] = val

            # Recursively solve the puzzle with the new value
            if solve_sudoku(board):
                return True

            # If the puzzle cannot be solved with the new value, backtrack
            board[empty_cell[0]][empty_cell[1]] = 0

    # If none of the values work, the puzzle is unsolvable
    return False


def find_empty_cell(board):
    """
    Find an empty cell in the Sudoku puzzle.

    :param board: 9x9 matrix representing the Sudoku puzzle
    :return: Tuple representing the row and column of an empty cell, or None if there are no empty cells
    """
    for row in range(9):
        for col in range(9):
            if board[row][col] == 0:
                return (row, col)
    return None


def is_valid_move(board, row, col, val):
    """
    Check if a move is valid in the Sudoku puzzle.

    :param board: 9x9 matrix representing the Sudoku puzzle
    :param row: Row of the cell to fill
    :param col: Column of the cell to fill
    :param val: Value to fill the cell with
    :return: True if the move is valid, False otherwise
    """
    # Check if the value is already in the row or column
    for i in range(9):
        if board[row][i] == val:
            return False
        if board[i][col] == val:
            return False

    # Check if the value is already in the square
    square_row = (row // 3) * 3
    square_col = (col // 3) * 3
    for i in range(3):
        for j in range(3):
            if board[square_row + i][square_col + j] == val:
                return False

    # If the value is not already in the row, column, or square, it is a valid move
    return True

在上面的代码中,solve_sudoku 函数使用回溯法解决数独问题。它首先查找一个空单元格,然后尝试在该单元格中填入值。如果该值是有效的,则递归地解决填入该值后的数独问题。如果递归调用返回 True,则说明该数独问题已经解决。否则,它会撤消该值并尝试下一个可能的值。如果没有可能的值,则该数独问题无解。

find_empty_cell 函数查找数独问题中的一个空单元格。如果没有空单元格,则该函数返回 None

is_valid_move 函数检查在给定的行和列中填写给定值是否有效。它首先检查该值是否已经在该行或列中。然后,它检查该值是否已经在该行和列所在的3x3方块中。如果值不在该行、列或3x3方块中,则该值是有效的

算法回溯法解决九宫格数度问题代码

原文地址: https://www.cveoy.top/t/topic/eGyr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录