-
Notifications
You must be signed in to change notification settings - Fork 1
/
Sudoku.py
119 lines (92 loc) · 2.94 KB
/
Sudoku.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
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
import time
# Settings
start_time = time.time()
class Sudoku():
def __init__(self):
self.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]]
self.size = len(self.board[0])
self.choices = [-1 if self.board[i][j] else 1
for i in range(self.size)
for j in range(self.size)]
self.x = 0
self.y = 0
def plot(self):
cn = 0
for row in self.board:
print(row)
for _ in row:
if _ != 0:
cn += 1
print('===========================', cn)
def row(self, n):
return n in self.board[self.y]
def col(self, n):
return n in [self.board[_][self.x]
for _ in range(9)]
def square(self, n):
return n in [self.board[b][a]
for a in range(self.x//3*3, self.x//3*3+3)
for b in range(self.y//3*3, self.y//3*3+3)]
def collision(self, n):
if self.row(n) or\
self.col(n) or\
self.square(n):
return True
else: return False
def backward(self):
self.board[self.y][self.x] = 0
self.choices[self.c] = 1
if self.x == 0:
self.x = 8
self.y -= 1
else:
self.x -= 1
while self.choices[self.y * self.size + self.x] == -1:
if self.x == 0:
self.x = 8
self.y -= 1
else:
self.x -= 1
def forward(self):
if self.x == 8:
self.x = 0
self.y += 1
else:
self.x += 1
def isEnd(self):
for row in self.board:
if 0 in row:
return False
return True
def run(self):
while not self.isEnd():
self.c = self.y*self.size+self.x
if self.choices[self.c] != -1:
if self.collision(self.choices[self.c]):
# Error
if self.choices[self.c] != 9:
self.choices[self.c] += 1
continue
# Back
else:
self.backward()
# Success
else:
self.board[self.y][self.x] = self.choices[self.c]
# plot()
self.forward()
else:
self.forward()
self.plot()
print('time:', time.time()-start_time)
if __name__ == '__main__':
s = Sudoku()
s.run()