I am creating a recursive algorithm to brute force a Sudoku puzzle. I have gotten everything to work properly, however, I am trying to figure out how to stop the process once it correctly finishes a puzzle. Here is what I have so far.
def solve(board, cell):
#calculate row and column of board
row = cell // 9
col = cell - (row*9)
#check if unfilled cell
if board[row][col] == 0:
#calculates possible numbers for cell
nums = getCandidates(row, col)
#if no possibilities previous cell must be wrong
if(len(nums) == 0):
return 0
#Iterate all possibilities assume each num is correct until proven wrong
for i in nums:
board[row][col] = i
solve(board, cell + 1)
#No possibilities were correct previous cell must be wrong
#Clear current cell and return to previous instance of solve()
board[row][col] = 0
else:
#Cell already filled skip to next
solve(board, cell+1)
I need a exit statement that would exit all recursive calls once puzzle solution is reached. I can't figure out how to do this and could use help. I would also, in the future, like to add a feature where the algorithm will continue past a solution checking for any other possible solutions. Keep this in mind so the exit statement would be adaptable for this. Thanks!
I could provide you with exact code that works, but
So here's a more general hint - you can rework your algorithm to work like this:
Basically, make use of
solve()
return values and check them each time you call it recursively. It is very common approach in brute force oriented searches. I.e. make use of that0
(which should beFalse
BTW) you return in one place, add somereturn True
and anif
... and you're set.Note that brute forcing sudoku puzzles, while might be good educational experience, is not the best approach in general.