Skip to content

Instantly share code, notes, and snippets.

@carterprince
Created May 20, 2023 18:17
Show Gist options
  • Save carterprince/c8b33c470ff831ff6e0130b91185a61e to your computer and use it in GitHub Desktop.
Save carterprince/c8b33c470ff831ff6e0130b91185a61e to your computer and use it in GitHub Desktop.
# Define the board
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 is_valid(board, row, col, num):
# Constraint 1: Each number must appear only once in each row.
for x in range(9):
if board[row][x] == num:
return False
# Constraint 2: Each number must appear only once in each column.
for x in range(9):
if board[x][col] == num:
return False
# Constraint 3: Each number must appear only once in each 3x3 box.
startRow = row - row % 3
startCol = col - col % 3
for i in range(3):
for j in range(3):
if board[i + startRow][j + startCol] == num:
return False
return True
def solve_sudoku(board):
for i in range(9):
for j in range(9):
# Find an unfilled cell
if board[i][j] == 0:
for num in range(1,10):
# Check if placing 'num' in the unfilled cell violates any constraint
if is_valid(board, i, j, num):
# Assign 'num' to the cell as it doesn't violate any constraint
board[i][j] = num
# Recursively attempt to fill the rest of the grid
if solve_sudoku(board):
return True
# If no valid arrangement could be found, undo the current cell assignment
board[i][j] = 0
# If no number can be assigned to this cell, backtrack
return False
# All cells are filled successfully
return True
if __name__ == "__main__":
if (solve_sudoku(board)):
print(board)
else:
print("No solution exists")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment