Last active
September 28, 2021 01:44
-
-
Save zedchance/8e9540f935fafc504e1e269eb2e21ffb to your computer and use it in GitHub Desktop.
Backtracking sudoku solver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Sudoku puzzle solver | |
def make_sudoku_board(): | |
return [ | |
[5, 3, 0, 0, 7, 0, 0, 0, 0], | |
[6, 0, 0, 1, 9, 5, 0, 0, 0], | |
[0, 9, 8, 0, 0, 0, 0, 6, 0], | |
[8, 0, 0, 0, 6, 0, 0, 0, 3], | |
[4, 0, 0, 8, 0, 3, 0, 0, 1], | |
[7, 0, 0, 0, 2, 0, 0, 0, 6], | |
[0, 6, 0, 0, 0, 0, 2, 8, 0], | |
[0, 0, 0, 4, 1, 9, 0, 0, 5], | |
[0, 0, 0, 0, 8, 0, 0, 7, 9], | |
] | |
def print_board(board): | |
for row in board: | |
for col in row: | |
print(col, end=" ") | |
print() | |
def solve(board): | |
def get_nums(row, col): | |
nums = [i for i in range(1, 10)] | |
# eliminate nums from row | |
for r in board[row]: | |
try: | |
nums.remove(r) | |
except: | |
pass | |
# eliminate nums from col | |
for r in board: | |
try: | |
nums.remove(r[col]) | |
except: | |
pass | |
# eliminate nums from matrix | |
mat_row = 3 * (row // 3) | |
mat_col = 3 * (col // 3) | |
for i in range(mat_row, mat_row + 3): | |
for j in range(mat_col, mat_col + 3): | |
try: | |
nums.remove(board[i][j]) | |
except: | |
pass | |
return nums | |
def _solve(row, col): | |
if row == 9 and col == 0: | |
print("\nSOLUTION:") | |
print_board(board) | |
elif board[row][col] == 0: | |
for t in get_nums(row, col): | |
# choose | |
board[row][col] = t | |
# explore | |
_solve(row if col < 8 else row + 1, (col + 1) % 9) | |
# unchoose | |
board[row][col] = 0 | |
else: | |
_solve(row if col < 8 else row + 1, (col + 1) % 9) | |
_solve(0, 0) | |
if __name__ == '__main__': | |
board = make_sudoku_board() | |
print_board(board) | |
solve(board) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output