Skip to content

Instantly share code, notes, and snippets.

@thanakijwanavit
Created February 12, 2023 02:10
Show Gist options
  • Save thanakijwanavit/d7ea46158df77f5335b7eef291595336 to your computer and use it in GitHub Desktop.
Save thanakijwanavit/d7ea46158df77f5335b7eef291595336 to your computer and use it in GitHub Desktop.
heuristic sudoku solution
def solve(grid):
empty_cell = find_empty_cell(grid)
if not empty_cell:
return grid
row, col = empty_cell
possible_numbers = get_possible_numbers(grid, row, col)
for num in possible_numbers:
grid[row][col] = num
solved_grid = solve(grid)
if solved_grid:
return solved_grid
grid[row][col] = 0
return None
def find_empty_cell(grid):
min_possible_numbers = float("inf")
empty_cell = None
for row in range(9):
for col in range(9):
if grid[row][col] == 0:
possible_numbers = len(get_possible_numbers(grid, row, col))
if possible_numbers < min_possible_numbers:
min_possible_numbers = possible_numbers
empty_cell = (row, col)
return empty_cell
def get_possible_numbers(grid, row, col):
used_numbers = set(grid[row][i] for i in range(9)) | \
set(grid[i][col] for i in range(9))
row_start = (row // 3) * 3
col_start = (col // 3) * 3
used_numbers |= {grid[row_start + i][col_start + j] for i in range(3) for j in range(3)}
return [num for num in range(1, 10) if num not in used_numbers]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment