Skip to content

Instantly share code, notes, and snippets.

@alex-md
Created September 2, 2022 17:59
Show Gist options
  • Save alex-md/1c760fe920df515fcf0ceb87f1ff7112 to your computer and use it in GitHub Desktop.
Save alex-md/1c760fe920df515fcf0ceb87f1ff7112 to your computer and use it in GitHub Desktop.
Solves sudoku puzzles
import itertools
ROWS = 9
COLS = 9
CELLS = ROWS * COLS
board = [
[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 solve_board(ROWS, COLS, board):
# Print the board
print("Initial board:")
print("-" * 25)
for i in range(ROWS):
row = "| "
for j in range(COLS):
row += str(board[i][j]) + " "
if (j + 1) % 3 == 0:
row += "| "
print(row)
if (i + 1) % 3 == 0:
print("-" * 25)
print()
# Solve the board
solved = False
while not solved:
solved = True
for i, j in itertools.product(range(ROWS), range(COLS)):
if board[i][j] == 0:
solved = False
possible = set(range(1, 10))
for k in range(ROWS):
possible.discard(board[i][k])
possible.discard(board[k][j])
for k, l in itertools.product(range(3), range(3)):
possible.discard(board[3 * (i // 3) + k][3 * (j // 3) + l])
if len(possible) == 1:
board[i][j] = possible.pop()
print("Solved board:")
print("-" * 25)
for i in range(ROWS):
row = "| "
for j in range(COLS):
row += str(board[i][j]) + " "
if (j + 1) % 3 == 0:
row += "| "
print(row)
if (i + 1) % 3 == 0:
print("-" * 25)
print()
solve_board(ROWS, COLS, board)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment