-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path數獨.py
89 lines (73 loc) · 2.69 KB
/
數獨.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import tkinter as tk
from tkinter import messagebox
class Sudoku:
def __init__(self, root):
self.root = root
self.root.title("數獨")
self.board = [[0] * 9 for _ in range(9)]
self.entries = [[None] * 9 for _ in range(9)]
self.create_widgets()
def create_widgets(self):
for row in range(9):
for col in range(9):
entry = tk.Entry(self.root, width=2, font=('Arial', 24), justify='center')
entry.grid(row=row, column=col, padx=5, pady=5)
self.entries[row][col] = entry
solve_button = tk.Button(self.root, text="解決", command=self.solve)
solve_button.grid(row=9, column=0, columnspan=4)
clear_button = tk.Button(self.root, text="清除", command=self.clear)
clear_button.grid(row=9, column=5, columnspan=4)
def solve(self):
self.read_board()
if self.solve_sudoku():
self.update_board()
else:
messagebox.showinfo("數獨", "無法解決此數獨")
def read_board(self):
for row in range(9):
for col in range(9):
value = self.entries[row][col].get()
self.board[row][col] = int(value) if value.isdigit() else 0
def update_board(self):
for row in range(9):
for col in range(9):
self.entries[row][col].delete(0, tk.END)
self.entries[row][col].insert(0, str(self.board[row][col]))
def clear(self):
for row in range(9):
for col in range(9):
self.entries[row][col].delete(0, tk.END)
self.board[row][col] = 0
def solve_sudoku(self):
empty = self.find_empty()
if not empty:
return True
row, col = empty
for num in range(1, 10):
if self.is_valid(num, row, col):
self.board[row][col] = num
if self.solve_sudoku():
return True
self.board[row][col] = 0
return False
def find_empty(self):
for row in range(9):
for col in range(9):
if self.board[row][col] == 0:
return (row, col)
return None
def is_valid(self, num, row, col):
for i in range(9):
if self.board[row][i] == num or self.board[i][col] == num:
return False
box_row = row // 3 * 3
box_col = col // 3 * 3
for i in range(3):
for j in range(3):
if self.board[box_row + i][box_col + j] == num:
return False
return True
if __name__ == "__main__":
root = tk.Tk()
game = Sudoku(root)
root.mainloop()