保存结果数独回溯
Posted
技术标签:
【中文标题】保存结果数独回溯【英文标题】:Save Result Sudoku Backtracking 【发布时间】:2020-11-09 13:57:48 【问题描述】:我在 python 中实现了回溯算法来解决数独问题。在我检查的算法步骤中,如果数独已经解决,当它解决时,我想返回它。但我的函数只返回无。有人可以解释一下原因并给我一个解决方案的提示吗?
#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)
【问题讨论】:
您的solve()
是递归的。但是,您不会利用对solve()
的递归调用的结果。你有return (grid)
,当然,但是调用者对这些结果没有做任何事情。
【参考方案1】:
因为你使用了return
,它返回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)
【讨论】:
以上是关于保存结果数独回溯的主要内容,如果未能解决你的问题,请参考以下文章