Skip to content

Instantly share code, notes, and snippets.

@zedchance
Last active September 28, 2021 01:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zedchance/8e9540f935fafc504e1e269eb2e21ffb to your computer and use it in GitHub Desktop.
Save zedchance/8e9540f935fafc504e1e269eb2e21ffb to your computer and use it in GitHub Desktop.
Backtracking sudoku solver
# 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)
@zedchance
Copy link
Author

Output

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 

SOLUTION:
5 3 4 6 7 8 9 1 2 
6 7 2 1 9 5 3 4 8 
1 9 8 3 4 2 5 6 7 
8 5 9 7 6 1 4 2 3 
4 2 6 8 5 3 7 9 1 
7 1 3 9 2 4 8 5 6 
9 6 1 5 3 7 2 8 4 
2 8 7 4 1 9 6 3 5 
3 4 5 2 8 6 1 7 9 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment