Skip to content

Instantly share code, notes, and snippets.

@Treebug842
Created July 24, 2020 06:36
Show Gist options
  • Save Treebug842/b2674e4bf7072979bfd43aa2f10bf8a3 to your computer and use it in GitHub Desktop.
Save Treebug842/b2674e4bf7072979bfd43aa2f10bf8a3 to your computer and use it in GitHub Desktop.
Simple code that solves a sodoku board using backtracking algorithm
#!/bin/env python3
# Written by Treebug842
board = [
[9, 0, 7, 0, 2, 1, 0, 0, 8],
[0, 1, 4, 0, 6, 0, 0, 9, 0],
[0, 0, 8, 5, 0, 7, 0, 0, 2],
[0, 4, 0, 9, 0, 0, 5, 1, 0],
[0, 2, 0, 0, 0, 0, 0, 6, 0],
[0, 7, 3, 0, 0, 5, 0, 2, 0],
[4, 0, 0, 1, 0, 9, 3, 0, 0],
[0, 3, 0, 0, 5, 0, 4, 8, 0],
[6, 0, 0, 8, 4, 0, 2, 0, 1]
]
def print_board(bo):
rowCount = 0
colCount = 0
lCount = 0
for x in range(len(bo)):
for y in range(len(bo)):
print(f" {bo[x][y]} ", end="")
rowCount += 1
colCount += 1
if rowCount == 9:
rowCount = 0
colCount = 0
lCount += 1
if lCount == 3:
print("\n- - - - - - - - - - - - - - -")
lCount = 0
else:
print("\n", end="")
if colCount == 3:
print("|", end="")
colCount = 0
def find_empty():
for row in range((len(board))):
for col in range(len(board)):
if board[row][col] == 0:
return (row, col)
return None
def valid(num, row, col):
for x in range(len(board)):
if board[row][x] == num:
return False
for y in range(len(board)):
if board[y][col] == num:
return False
box_x = row // 3
box_y = col // 3
for x in range(box_x * 3, box_x * 3 + 3):
for y in range(box_y * 3, box_y * 3 + 3):
if board[x][y] == num and (x, y) != (row, col):
return False
return True
def solve():
empty = find_empty()
if not empty:
return True
else:
row, col = empty
for num in range(1, 10):
if valid(num, row, col):
board[row][col] = num
if solve():
return True
board[row][col] = 0
return False
if solve():
print("Completed")
else:
print("Failed")
print_board(board)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment