-
Notifications
You must be signed in to change notification settings - Fork 0
/
normal_sudoku.py
136 lines (101 loc) · 3.01 KB
/
normal_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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
import copy
cur_map = []
stack = []
n = 0
class Cell:
def __init__(self,x,y,number):
self.x = x
self.y = y
self.isComplete = False
if number != '*' :
self.isComplete = True
number = int(number)
self.number = number
self.num_mrv = [x for x in range(1,n+1)]
def __repr__(self):
return "{}".format(self.number)
def get_input():
print("here")
for i in range(n):
cur_map.append([])
for i in range(n):
col = 0
for j in input().split(" "):
cur_map[i].append(Cell(i,col,j))
col = col +1
def set_cell_num_domain(cell):
x = cell.x
y = cell.y
if cell.number != '*':
for i in range(n):
if i == x :# or cur_map[i][y].isComplete == True :
continue
try:
cur_map[i][y].num_mrv.remove(cell.number)
if len(cur_map[i][y].num_mrv) == 0 and cur_map[i][y].isComplete != True:
return false
except:
pass
for j in range(n):
if j == y: # or cur_map[x][j].isComplete == True:
continue
try:
cur_map[x][j].num_mrv.remove(cell.number)
if len(cur_map[x][j].num_mrv) == 0 and cur_map[x][j].isComplete != True:
return False
except:
pass
return True
def set_map_domain():
for i in range(n):
for j in range(n):
x = set_cell_num_domain(cur_map[i][j])
return x
def print_mrv():
for i in range(n):
for j in range(n):
print(cur_map[i][j].num_mrv,end=",,,")
print()
def choose_cell():
min_mrv_cell = Cell(-1,-1,"*")
min_mrv_cell.num_mrv=[x for x in range(n+1)]
for i in range(n):
for j in range(n):
if cur_map[i][j].isComplete == False and len(cur_map[i][j].num_mrv) <= len(min_mrv_cell.num_mrv) :
min_mrv_cell = cur_map[i][j]
return min_mrv_cell
def forward_checking(cell):
x = set_cell_num_domain(cell)
if x == False:
return "failuer"
n = int(input("enter n: \n"))
get_input()
set_map_domain()
print("map for first time: \n")
for i in range(n):
print(cur_map[i])
print("*********")
stack.append(cur_map)
while len(stack)>0:
chosen_cell = choose_cell()
# print("chosen is",chosen_cell.x,chosen_cell.y)
if (chosen_cell.x == -1 or chosen_cell.y == -1):
print("result: ")
for i in range(n):
print(cur_map[i])
exit()
if len(chosen_cell.num_mrv ) == 0:
t = "failuer"
else:
x = chosen_cell.num_mrv.pop(0)
bp_map = copy.deepcopy(cur_map)
stack.append(bp_map)
chosen_cell.number = x
chosen_cell.isComplete = True
t = forward_checking(chosen_cell)
if t != "failuer":
pass
else:
print("back Track".center(40,"*"))
cur_map = stack.pop()
print("no solution")