需要数据解算器Python算法澄清

时间:2017-10-17 18:11:18

标签: python backtracking sudoku

我在python中构建了一个数独求解器回溯算法,只是为了发现它不起作用。我查看了互联网上的例子,发现与我的相比,他们只做了一件不同的事情。我相应地更改了我的代码,我的程序现在运行正常。

以下是工作代码:

sudoku = []
next_empty_pos = [0,0]

# Check if the number is already used in the given row
def valid_in_row(number,row):
    for i in range(9):
        if(sudoku[row][i] == number):
            return False
    return True

# Check if the number is already used in the given column
def valid_in_col(number,col):
    for i in range(9):
        if(sudoku[i][col] == number):
            return False;
    return True;

# Check if the number is already used in the given 3x3 box
def valid_in_box(number,row,col):
    # Find where 3x3 row and col starts
    col_start = col-col%3
    row_start = row-row%3
    # Loop through the 3 columns and 3 rows
    for i in range(3):
        for z in range(3):
            if(sudoku[i+row_start][z+col_start] == number):
                return False
    return True

# Check if the position is valid for the given number by checking all three conditions above
def position_valid(number,row,col):
    return valid_in_row(number,row) and valid_in_col(number,col) and valid_in_box(number,row,col)

# Find if there are any empty cells left and assign the next empty cell
def empty_position_exists():
    for row in range(9):
        for col in range(9):
            if(sudoku[row][col] == 0):
                global next_empty_pos
                next_empty_pos = [row,col]
                return True
    return False

# Solve the sudoku
def solve_sudoku():

    # If there are no more empty cells, we are finished
    if(not empty_position_exists()):
        return True

    row=next_empty_pos[0]
    col=next_empty_pos[1]

    # Try numbers from 1
    for posssible_number in range(1,10):

        if(position_valid(posssible_number,row,col)):

            sudoku[row][col] = posssible_number

            # If the next function call evalutes to true, then this should be true as well
            if(solve_sudoku()):
                return True

            # If the above did not work then, set the number back to 0 (unassgined)
            sudoku[row][col] = 0

    # Return false if none of the numbers were good
    return False

与原始代码的不同之处在于,我直接在next_empty_pos[0]函数中传递了next_empty_pos[1]solve_sudoku,并未将它们声明为单独row和{{1}变量在for循环之外。

我的功能看起来像这样:

col

有人可以解释为什么我的版本无效吗?

提前致谢。

1 个答案:

答案 0 :(得分:0)

empty_position_exists更改next_empty_pos。当solve_sudoku以递归方式调用自身时,将从递归调用中调用empty_position_exists,从而更改next_empty_pos。结果是,在递归调用返回后访问这些值时,它们已更改。这就是两个版本表现不同的原因。