-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSudoku_Solver_9_by_9.py
More file actions
134 lines (108 loc) · 2.29 KB
/
Copy pathSudoku_Solver_9_by_9.py
File metadata and controls
134 lines (108 loc) · 2.29 KB
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
import tkinter as tk
def run():
global sudoku_grid
sudoku_grid = []
for i in entries:
e = []
for j in i:
e.append(j.get().strip())
sudoku_grid.append(e)
if solve_sudoku(0, 0):
result_window()
else:
tk.Label(s, text='This sudoku has no solution', fg='red').place(x=110, y=315)
def result_window():
result = tk.Toplevel(s)
result.title('Result')
result.geometry('400x400')
j = 0
for i in range(50, 320, 30):
tk.Label(result, text=' '.join(sudoku_grid[j])).place(x=110, y=i)
j += 1
def issafe(r, c, n):
for x in range(9):
if sudoku_grid[r][x] == n:
return False
for x in range(9):
if sudoku_grid[x][c] == n:
return False
startRow = r - r % 3
startCol = c - c % 3
for i in range(3):
for j in range(3):
if sudoku_grid[i + startRow][j + startCol] == n:
return False
return True
def solve_sudoku(r, c):
if r == 8 and c == 9:
return True
if c == 9:
r += 1
c = 0
if sudoku_grid[r][c] != '':
return solve_sudoku(r, c + 1)
for num in range(1, 10, 1):
if issafe(r, c, str(num)):
sudoku_grid[r][c] = str(num)
if solve_sudoku(r, c + 1):
return True
sudoku_grid[r][c] = ''
return False
s = tk.Tk()
s.title('Sudoku Solver')
s.geometry('400x400')
w = tk.Label(s, text='Unknown numbers leave it blank', fg='blue').place(x=98, y=10)
entries = []
for i in range(50, 320, 30):
e = []
for j in range(60, 330, 30):
entry = tk.Entry(s, width=3, justify='center')
entry.place(x=j, y=i)
e.append(entry)
entries.append(e)
submit = tk.Button(s, text='Submit', width=25, command=run).place(x=100, y=340)
s.mainloop()
'''
Sample Input 1
1.45..89.
.963..5.1
53.41....
6......25
2.9...3.7
48......6
....37.54
9.7..563.
.45..12.9
Sample Output 1
124576893
796328541
538419762
671893425
259164387
483752916
862937154
917245638
345681279
'''
'''
Sample Input 2
9...28.57
5...192.3
.3.5...6.
.8.2..395
...7.6...
341..5.2.
.6...7.3.
1.895...4
75.46...9
Sample Output 2
916328457
574619283
832574961
687241395
295736148
341895726
469187532
128953674
753462819
'''