保存结果数独回溯

Save Result Sudoku Backtracking

我在 python 中实现了回溯算法来解决数独问题。在我检查的算法步骤中,如果数独已经解决了,我想 return 它。但是我的函数只是 returns None。有人可以向我解释一下原因并给我一个解决方案的提示吗?

#Test-Sudoku
grid = [[1,0,7,0,0,5,4,0,0],
        [9,0,0,3,7,0,0,0,0],
        [0,2,3,0,8,0,0,0,0],
        [0,9,2,0,0,0,0,7,0],
        [0,7,0,0,6,0,0,1,0],
        [0,6,0,0,0,0,8,9,0],
        [0,0,0,0,4,0,3,6,0],
        [0,0,0,0,3,7,0,0,1],
        [0,0,8,2,0,0,5,0,7]]


def possible(row,col,num,grid):
    """ Check if num can be passed to grid[row][col]"""
    if grid[row][col] != 0:
        return False
    for i in range(9):
        if grid[row][i] == num or grid[i][col] == num:
            return False
    row0 = (row//3)*3
    col0 = (col//3)*3
    for i in range(3):
        for j in range(3):
            if grid[row0+i][col0+j] == num:
                return False
    return True

def is_solved(grid):
    """ Check if Sudoku is already solved/full"""
    for i in range(9):
        for j in range(9):
            if grid[i][j] == 0:
                return False
    return True


def solve(grid):
    """ Backtracking algorithm to solve Sudoku"""
    for r in range(9):
        for c in range(9):
            if grid[r][c] == 0:
                for i in range(1,10):
                    if possible(r, c, i, grid): 
                        grid[r][c] = i
                        if is_solved(grid):
                            # Print grid for test
                            print("Show Solved Sudoku:")
                            print(grid)
                            return(grid) 
                        solve(grid)
                        grid[r][c] = 0
                return 
    return 
    

solved_sudoku = solve(grid)

print(solved_sudoku)

因为您使用了 return,其中 returns none
您将结果存储在 grid 中,并且 grid 每次变化

试试这个:

def solve(grid):
    """ Backtracking algorithm to solve Sudoku"""
    for r in range(9):
        for c in range(9):
            if grid[r][c] == 0:
                for i in range(1,10):
                    if possible(r, c, i, grid): 
                        grid[r][c] = i 
                        solve(grid)
                    if is_solved(grid):
                        return
                    grid[r][c] = 0
                return

solve(grid)
print(grid)