Take care of some edge cases in the backtracker

This commit is contained in:
Eryn Wells 2017-10-11 20:25:11 -07:00
parent a9a331df91
commit 3b380b17d2

View file

@ -12,21 +12,21 @@ def solve(sudoku):
return _solve_square(sudoku, 0, 0)
def _solve_square(sudoku, x, y):
should_backtrack = False
for value in sudoku.possible_values:
should_backtrack = False
try:
print('({},{}) trying {}'.format(x, y, value))
sudoku.set(x, y, value)
except SquareIsClue:
# Do nothing with this square; continue on to the next square below.
print('({},{}) square is clue'.format(x,y))
pass
except ValueExistsInPeers:
print('({},{}) value exists in peer set'.format(x,y))
# Try next value.
should_backtrack = True
continue
except NoPossibleValues:
# Need to backtrack.
print('({},{}) backtracking'.format(x,y))
sudoku.unset(x, y)
raise Backtrack()
next_coord = _next_coord(sudoku, x, y)
@ -34,9 +34,19 @@ def _solve_square(sudoku, x, y):
break
try:
_solve_square(sudoku, *next_coord)
return _solve_square(sudoku, *next_coord)
except Backtrack:
should_backtrack = True
continue
if should_backtrack:
# Unhandled backtrack. Pop out of this one too.
try:
sudoku.unset(x, y)
except SquareIsClue:
pass
raise Backtrack()
return sudoku
def _next_coord(sudoku, x, y):