Skip to content

Instantly share code, notes, and snippets.

@k-kondo-s
Created April 6, 2024 16:27
Show Gist options
  • Save k-kondo-s/68f439041b91d786ea55965278b8f7bc to your computer and use it in GitHub Desktop.
Save k-kondo-s/68f439041b91d786ea55965278b8f7bc to your computer and use it in GitHub Desktop.
sudoku_solution.py
# %%
from PIL import Image, ImageDraw, ImageFont
def is_valid(board, row, col, num):
# Check row
for i in range(9):
if board[row][i] == num:
return False
# Check column
for i in range(9):
if board[i][col] == num:
return False
# Check 3x3 box
start_row = (row // 3) * 3
start_col = (col // 3) * 3
for i in range(3):
for j in range(3):
if board[start_row + i][start_col + j] == num:
return False
return True
def solve_sudoku(board, gif_frames):
display_board_image(board, gif_frames)
for row in range(9):
for col in range(9):
if board[row][col] == 0:
for num in range(1, 10):
if is_valid(board, row, col, num):
board[row][col] = num
if solve_sudoku(board, gif_frames):
return True
board[row][col] = 0
return False
return True
def display_board_image(board, gif_frames):
cell_size = 50
grid_size = cell_size * 9
image = Image.new("RGB", (grid_size, grid_size), color="white")
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("Arial Unicode.ttf", 60)
# 外側の縁を描画
draw.rectangle((0, 0, grid_size - 1, grid_size - 1), outline="black", width=2)
for i in range(9):
for j in range(9):
if board[i][j] != 0:
x = j * cell_size + cell_size // 2
y = i * cell_size + cell_size // 2
draw.text(
(x, y), str(board[i][j]), font=font, anchor="mm", fill="black"
)
for i in range(10):
line_width = 2 if i % 3 == 0 else 1
draw.line(
(0, i * cell_size, grid_size, i * cell_size), fill="black", width=line_width
)
draw.line(
(i * cell_size, 0, i * cell_size, grid_size), fill="black", width=line_width
)
# 外側の縁をもう一度描画
draw.rectangle((0, 0, grid_size - 1, grid_size - 1), outline="black", width=2)
gif_frames.append(image)
def save_gif(gif_frames, filename, duration=500, last_frame_duration=10000):
# 最後のフレームを複製
last_frame = gif_frames[-1].copy()
# 最後のフレームを追加
gif_frames.append(last_frame)
# フレームの表示時間を設定
durations = [duration] * (len(gif_frames) - 1) + [last_frame_duration]
gif_frames[0].save(
filename,
save_all=True,
append_images=gif_frames[1:],
optimize=False,
duration=durations,
loop=0,
)
board = [
[8, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 3, 6, 0, 0, 0, 0, 0],
[0, 7, 0, 0, 9, 0, 2, 0, 0],
[0, 5, 0, 0, 0, 7, 0, 0, 0],
[0, 0, 0, 0, 4, 5, 7, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 3, 0],
[0, 0, 1, 0, 0, 0, 0, 6, 8],
[0, 0, 8, 5, 0, 0, 0, 1, 0],
[0, 9, 0, 0, 0, 0, 4, 0, 0],
]
gif_frames = []
solve_sudoku(board, gif_frames)
save_gif(gif_frames, "sudoku_solution.gif", duration=5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment