Take care of some edge cases in the backtracker
This commit is contained in:
parent
a9a331df91
commit
3b380b17d2
1 changed files with 15 additions and 5 deletions
|
@ -12,21 +12,21 @@ def solve(sudoku):
|
||||||
return _solve_square(sudoku, 0, 0)
|
return _solve_square(sudoku, 0, 0)
|
||||||
|
|
||||||
def _solve_square(sudoku, x, y):
|
def _solve_square(sudoku, x, y):
|
||||||
|
should_backtrack = False
|
||||||
for value in sudoku.possible_values:
|
for value in sudoku.possible_values:
|
||||||
|
should_backtrack = False
|
||||||
try:
|
try:
|
||||||
print('({},{}) trying {}'.format(x, y, value))
|
|
||||||
sudoku.set(x, y, value)
|
sudoku.set(x, y, value)
|
||||||
except SquareIsClue:
|
except SquareIsClue:
|
||||||
# Do nothing with this square; continue on to the next square below.
|
# Do nothing with this square; continue on to the next square below.
|
||||||
print('({},{}) square is clue'.format(x,y))
|
|
||||||
pass
|
pass
|
||||||
except ValueExistsInPeers:
|
except ValueExistsInPeers:
|
||||||
print('({},{}) value exists in peer set'.format(x,y))
|
|
||||||
# Try next value.
|
# Try next value.
|
||||||
|
should_backtrack = True
|
||||||
continue
|
continue
|
||||||
except NoPossibleValues:
|
except NoPossibleValues:
|
||||||
# Need to backtrack.
|
# Need to backtrack.
|
||||||
print('({},{}) backtracking'.format(x,y))
|
sudoku.unset(x, y)
|
||||||
raise Backtrack()
|
raise Backtrack()
|
||||||
|
|
||||||
next_coord = _next_coord(sudoku, x, y)
|
next_coord = _next_coord(sudoku, x, y)
|
||||||
|
@ -34,9 +34,19 @@ def _solve_square(sudoku, x, y):
|
||||||
break
|
break
|
||||||
|
|
||||||
try:
|
try:
|
||||||
_solve_square(sudoku, *next_coord)
|
return _solve_square(sudoku, *next_coord)
|
||||||
except Backtrack:
|
except Backtrack:
|
||||||
|
should_backtrack = True
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
if should_backtrack:
|
||||||
|
# Unhandled backtrack. Pop out of this one too.
|
||||||
|
try:
|
||||||
|
sudoku.unset(x, y)
|
||||||
|
except SquareIsClue:
|
||||||
|
pass
|
||||||
|
raise Backtrack()
|
||||||
|
|
||||||
return sudoku
|
return sudoku
|
||||||
|
|
||||||
def _next_coord(sudoku, x, y):
|
def _next_coord(sudoku, x, y):
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue