Created
July 4, 2023 10:58
-
-
Save IanCal/9817f8b21b2ea6d77940966ee399d2de to your computer and use it in GitHub Desktop.
LLM generated sudoku solver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def find_empty(grid): | |
for i in range(9): | |
for j in range(9): | |
if grid[i][j] == 0: | |
return i, j # row, column | |
return None # no empty spaces in the grid | |
def is_valid(grid, num, pos): | |
# Check if num is already in the row or column | |
for i in range(9): | |
if grid[pos[0]][i] == num or grid[i][pos[1]] == num: | |
return False | |
# Check if num is already in the box | |
box_x = pos[1] // 3 | |
box_y = pos[0] // 3 | |
for i in range(box_y * 3, box_y * 3 + 3): | |
for j in range(box_x * 3, box_x * 3 + 3): | |
if grid[i][j] == num: | |
return False | |
return True | |
def solve(grid): | |
find = find_empty(grid) | |
if not find: | |
return True # all cells are filled | |
else: | |
row, col = find | |
for i in range(1, 10): # try digits from 1 to 9 | |
if is_valid(grid, i, (row, col)): | |
grid[row][col] = i | |
if solve(grid): # recursively try to fill the rest of the grid | |
return True | |
grid[row][col] = 0 # undo if no solution can be found | |
return False # no solution | |
grid = [ | |
[4,9,6,0,7,0,0,0,0], | |
[0,0,8,9,0,3,0,0,0], | |
[7,5,0,8,0,2,0,1,9], | |
[0,0,0,0,0,0,0,2,5], | |
[0,0,1,7,2,0,4,9,0], | |
[8,0,7,0,9,0,3,6,0], | |
[0,8,0,0,0,7,9,0,0], | |
[0,6,0,0,5,4,0,3,0], | |
[0,0,0,2,8,9,1,5,6] | |
] | |
print(solve( | |
grid | |
)) | |
for row in grid: | |
print(row) | |
grid = [ | |
[0,0,6,0,0,0,0,0,1], | |
[0,3,0,0,0,0,8,0,0], | |
[0,0,0,5,0,8,4,0,0], | |
[0,6,0,0,1,0,0,2,0], | |
[0,0,3,0,0,7,0,0,0], | |
[0,9,1,0,0,0,3,0,0], | |
[0,0,0,0,0,5,1,7,0], | |
[1,5,0,0,2,6,0,0,0], | |
[0,0,0,0,9,0,6,5,0], | |
] | |
print(solve( | |
grid | |
)) | |
for row in grid: | |
print(row) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment