【发布时间】:2020-10-13 14:29:08
【问题描述】:
我对编程很陌生,我最近开始研究 sudoko 求解器,除了求解算法本身之外,一切都很好,我从互联网上获得了一些帮助,但是因为我自己编写了方法,所以我可以'找不到我的代码的准确解决方案,任何帮助将不胜感激!
问题:代码一直运行,直到它无法在空 (0) 索引之一中输入值,而不是回溯,它只是停止。
如果你能让我知道我做错了什么,或者提出可能的方法来完全改进代码,那么任何事情都会有很大的帮助!
我的代码在这里:
import time
start_time = time.time()
grid = [
[7, 8, 0, 4, 0, 0, 1, 2, 0],
[6, 0, 0, 0, 7, 5, 0, 0, 9],
[0, 0, 0, 6, 0, 1, 0, 7, 8],
[0, 0, 7, 0, 4, 0, 2, 6, 0],
[0, 0, 1, 0, 5, 0, 9, 3, 0],
[9, 0, 4, 0, 6, 0, 0, 0, 5],
[0, 7, 0, 3, 0, 0, 0, 1, 2],
[1, 2, 0, 0, 0, 7, 4, 0, 0],
[0, 4, 9, 2, 0, 6, 0, 0, 7]
]
def printBoard():
print("Suduko Board")
for row in grid:
for elem in row:
print(elem, end=' ')
print()
def checkInRow(grid,row, num):
for i in range(0,9):
if(grid[row][i] == num):
return True
return False
def checkInCol(grid,col, num):
for i in range(0,9):
if(grid[i][col] == num):
return True
return False
def checkInBox(grid, row, col, num):
#This will give the starting point for the box
boxX = (row // 3) * 3
boxY = (col // 3) * 3
for i in range(3):
for j in range(3):
if((grid[boxY + j][boxX + i]) == num):
return True
return False
def findNextEmpty(grid, num):
for row in range(9):
for col in range(9):
if(grid[row][col] == num):
return row, col
return None
def checkSafe(grid, row, col, num): #Returns true if safe returns false if unsafe
return not checkInRow(grid,row,num) and not checkInCol(grid,col,num) and not checkInBox(grid,row,col,num)
#PROBLEM IS HERE \/
def solveSudoko(grid, i,j):
if not findNextEmpty(grid,0):
return True
else:
i = findNextEmpty(grid,0)[0] # Finds Row #
j = findNextEmpty(grid,0)[1] # Finds Col #
print(i, j)
for value in range(1,10):
if checkSafe(grid,i,j,value) == True:
grid[i][j] = value
printBoard()
print("--- %s seconds ---" % (time.time() - start_time))
if(solveSudoko(grid,i,j)):
return True
grid[i][j] = 0
return False
#print(str(value) + " can go in grid[" + str(i) + "]" + "[" + str(j) + "]")
printBoard()
solveSudoko(grid,0,0)
【问题讨论】:
-
How to debug small programs. | What is a debugger and how can it help me diagnose problems? 请使用这些链接中描述的技巧将您的代码压缩为 minimal reproducible example。也请拨打tour,并阅读How to Ask 和what's on-topic here。欢迎使用 Stack Overflow!
标签: python algorithm methods solver backtracking