-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.py
136 lines (108 loc) · 3.18 KB
/
util.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
from class_state import *
from class_list import *
import math
#heuristická funkce je součet vzdáleností všech "kamenů" od jejich finální pozice pošťáckou metrikou
def heur(state):
if state == None:
return math.inf
h = 0
for i in range(state.n):
for j in range(state.n):
if state.array[i][j] == 0:
dif = (state.n - i - 1) + (state.n - j - 1)
else:
final_i = (state.array[i][j] - 1) // state.n
final_j = (state.array[i][j] - 1) % state.n
dif = abs(final_i - i) + abs(final_j - j)
h = h + dif
h = h + state.g
return h
#expanze stavu
def expand(state):
#libovolný stav může být rodičem maximálně 4 různých stavů
successors = List(4)
if state == None:
return successors
#nalezení 0
i = 0
j = 0
for k in range(state.n):
for l in range(state.n):
if state.array[k][l] == 0:
i = k
j = l
break
else:
continue
break
#0 nahoru
if i != 0:
succ = copy.deepcopy(state)
succ.array[i][j] = succ.array[i - 1][j]
succ.array[i - 1][j] = 0
#rodič
succ.parent = copy.deepcopy(state)
#hloubka
succ.g = state.g + 1
successors.insert(succ)
#0 dolů
if i != state.n - 1:
succ = copy.deepcopy(state)
succ.array[i][j] = succ.array[i + 1][j]
succ.array[i + 1][j] = 0
succ.parent = copy.deepcopy(state)
succ.g = state.g + 1
successors.insert(succ)
#0 doleva
if j != 0:
succ = copy.deepcopy(state)
succ.array[i][j] = succ.array[i][j - 1]
succ.array[i][j - 1] = 0
succ.parent = copy.deepcopy(state)
succ.g = state.g + 1
successors.insert(succ)
#0 doprava
if j != state.n - 1:
succ = copy.deepcopy(state)
succ.array[i][j] = succ.array[i][j + 1]
succ.array[i][j + 1] = 0
succ.parent = copy.deepcopy(state)
succ.g = state.g + 1
successors.insert(succ)
return successors
#vyřešitelnost
def solvability(state):
K = -1
for k in range(state.n):
for l in range(state.n):
if state.array[k][l] == 0:
K = k + 1
break
else:
continue
break
row = [None for i in range(state.n * state.n)]
for i in range(state.n):
for j in range(state.n):
row[j + state.n * i] = state.array[i][j]
N = 0
for i in range(state.n * state.n):
for j in range(state.n * state.n - i):
if row[i + j] == 0:
continue
if row[i] > row[i + j]:
N += 1
print('K: ')
print(K)
print('N: ')
print(N)
if state.n % 2 == 0:
if (K + N) % 2 == 0:
return True
else:
return False
else:
if N % 2 == 0:
return True
else:
return False