Skip to content

Instantly share code, notes, and snippets.

@scwood
Last active February 14, 2016 01:13
Show Gist options
  • Save scwood/1ed741e0cc9060daff50 to your computer and use it in GitHub Desktop.
Save scwood/1ed741e0cc9060daff50 to your computer and use it in GitHub Desktop.
import re
class Solver(object):
def solve_sudoku(self, board):
if self._solve(board):
return board
return None
def _solve(self, board):
for r in range(9):
for c in range(9):
if board[r][c] == '.':
for d in '123456789':
if self._is_valid(board, r, c, d):
board[r][c] = d
if self._solve(board):
return True
board[r][c] = '.'
return False
return True
def _is_valid(self, board, r, c, d):
for row in range(9):
if board[row][c] == d:
return False
for col in range(9):
if board[r][col] == d:
return False
for row in range(r//3*3, r//3*3+3):
for col in range(c//3*3, c//3*3+3):
if board[row][col] == d:
return False
return True
if __name__ == '__main__':
board = []
valid = re.compile(r'^[1-9.]{9}$')
for i in range(9):
while True:
row = input('Row {0}: '.format(i+1))
if valid.match(row):
board.append(list(row))
break
print('Invalid input: row must only contain 1-9 and/or blanks represented by "."')
solver = Solver()
solution = solver.solve_sudoku(board)
if solution:
for l in solution:
print(''.join(l))
else:
print('Unsolvable')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment