Skip to content

Instantly share code, notes, and snippets.

@black-dragon74
Created December 2, 2020 21:19
Show Gist options
  • Save black-dragon74/b895d92298f908a95c2ea79c434b4318 to your computer and use it in GitHub Desktop.
Save black-dragon74/b895d92298f908a95c2ea79c434b4318 to your computer and use it in GitHub Desktop.
Solve sudoku fast AF
def find_next_empty(puzzle):
for r in range(9):
for c in range(9):
if puzzle[r][c] == 0:
return r, c
return None, None
def is_valid(guess, puzzle, row, col):
# First check the rows
row_vals = puzzle[row]
if guess in row_vals:
return False
# Then check the cols, a bit trciky but manageable
col_vals = [puzzle[c][col] for c in range(9)]
if guess in col_vals:
return False
# Now comes the matrix, my expectations for you were low but holy F!
mtx_row = (row // 3) * 3
mtx_col = (col // 3) * 3
for r in range(mtx_row, mtx_row + 3):
for c in range(mtx_col, mtx_col + 3):
if puzzle[r][c] == guess:
return False
return True
count = 0
def solve_sudoku(puzzle):
global count
count += 1
row, col = find_next_empty(puzzle)
# Means, there is nothing left to fill, base case for recursion
# It also means that problem is complete in language of hoomans
if row is None:
return True
# Otherwise, make a guess, and check if that guess is valid
for guess in range(1, 10):
if is_valid(guess, puzzle, row, col):
puzzle[row][col] = guess
if solve_sudoku(puzzle):
return True
puzzle[row][col] = 0
# Otherwise, by the power of GOD, I hereby declare that this puzzle is impossible to solve
return False
def printsudoku(sudoku):
print()
for i in range(len(sudoku)):
line = ""
if i == 3 or i == 6:
print("---------------------")
for j in range(len(sudoku[i])):
if j == 3 or j == 6:
line += "| "
line += str(sudoku[i][j]) + " "
print(line)
def run():
matrix = [
[0, 0, 5, 3, 0, 0, 0, 0, 0],
[8, 0, 0, 0, 0, 0, 0, 2, 0],
[0, 7, 0, 0, 1, 0, 5, 0, 0],
[4, 0, 0, 0, 0, 5, 3, 0, 0],
[0, 1, 0, 0, 7, 0, 0, 0, 6],
[0, 0, 3, 2, 0, 0, 0, 8, 0],
[0, 6, 0, 5, 0, 0, 0, 0, 9],
[0, 0, 4, 0, 0, 0, 0, 3, 0],
[0, 0, 0, 0, 0, 9, 7, 0, 0],
]
if solve_sudoku(matrix):
printsudoku(matrix)
print("\nSolved Sudoku successfully. It took me %d tries :]" % count)
else:
print("\nBy the law of GOD, this Sudoku is unsolvable.")
print("Trust me, I tried all %d possible combinations." % count)
if __name__ == '__main__':
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment