怎样解数独?
Python
def setBoardFunc(puz):
global grid
print("Original Sudoku")
for i in range(0, len(puz), 9):
row = puz[i:i+9]
temp = []
for block in row:
temp.append(int(block))
grid.append(temp)
printGridFunc()
def printGridFunc():
global grid
for row in grid:
print(row)
def checkValidFunc(row, column, num):
global grid
for i in range(9):
if grid[row][i] == num or grid[i][column] == num:
return False
square_row, square_col = (row // 3) * 3, (column // 3) * 3
for i in range(3):
for j in range(3):
if grid[square_row + i][square_col + j] == num:
return False
return True
def solveFunc(solutions_count=1):
global grid
solutions_found = 0 # 计数器,用于记录已找到的解的数量
def solve():
nonlocal solutions_found
for row in range(9):
for column in range(9):
if grid[row][column] == 0:
for num in range(1, 10):
if checkValidFunc(row, column, num):
grid[row][column] = num
solve()
grid[row][column] = 0 # 回溯
return
# 当所有空格都被填满时,找到了一个解
solutions_found += 1
print(f'\nSolution {solutions_found} to Sudoku Problem')
printGridFunc()
if solutions_found >= solutions_count: # 如果找到了指定数量的解,则停止搜索
raise StopIteration # 使用异常来退出递归
try:
solve()
except StopIteration:
pass # 捕获异常以优雅地结束递归
# 设置谜题和求解
puz = "800000000003600000070090200050007000000045700000100030001000068008500010090000400"
grid = []
setBoardFunc(puz)
solveFunc(solutions_count=2) # 更改这里的数字来设置输出的解的数量