From 65f4453e786dea7361b051a84d85df127cffe9fb Mon Sep 17 00:00:00 2001 From: Eryn Wells Date: Wed, 11 Oct 2017 19:45:00 -0700 Subject: [PATCH] Attempt #1 at a backtracking solver --- sudoku/solvers/__init__.py | 6 ++--- sudoku/solvers/backtracker.py | 48 +++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 4 deletions(-) create mode 100644 sudoku/solvers/backtracker.py diff --git a/sudoku/solvers/__init__.py b/sudoku/solvers/__init__.py index de3672c..becaaba 100644 --- a/sudoku/solvers/__init__.py +++ b/sudoku/solvers/__init__.py @@ -1,8 +1,6 @@ # Eryn Wells ''' +A library of Sudoku solvers. ''' -class Solver: - def solve(self, sudoku): - # TODO: Any subclass of Solver should implement this. - raise NotImplementedError +from . import backtracker diff --git a/sudoku/solvers/backtracker.py b/sudoku/solvers/backtracker.py new file mode 100644 index 0000000..62cd01e --- /dev/null +++ b/sudoku/solvers/backtracker.py @@ -0,0 +1,48 @@ +# Eryn Wells + +from .. import SquareIsClue, ValueExistsInPeers, NoPossibleValues + +class Backtrack(Exception): + pass + +def solve(sudoku): + ''' + Implements a recursive backtracking Sudoku solver. + ''' + return _solve_square(sudoku, 0, 0) + +def _solve_square(sudoku, x, y): + for value in sudoku.possible_values: + 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. + continue + except NoPossibleValues: + # Need to backtrack. + print('({},{}) backtracking'.format(x,y)) + raise Backtrack() + + next_coord = _next_coord(sudoku, x, y) + if not next_coord: + break + + try: + _solve_square(sudoku, *next_coord) + except Backtrack: + continue + return sudoku + +def _next_coord(sudoku, x, y): + x += 1 + if x >= sudoku.row_size: + (x, y) = (0, y + 1) + if y >= sudoku.row_size: + return None + return (x, y)