-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathastar.py
63 lines (43 loc) · 1.65 KB
/
astar.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
from heapq import heappop, heappush
import time
from schelet import NPuzzle
MAX_EXECUTION_TIME = 60 * 3
def get_neighbours(pos):
# Setam vecinii
neighbours = []
for i in NPuzzle.ACTIONS:
if pos.apply_move(i):
neighbours.append(pos.apply_move(i))
return neighbours
def astar(start, end, h):
start_time = time.time()
# Frontiera, ca listă (heap) de tupluri (cost-total-estimat, nod)
frontier = []
heappush(frontier, (0 + h(start), start))
# Nodurile descoperite ca dicționar nod -> (părinte, cost-până-la-nod)
discovered = {start: (None, 0)}
# Marim frontiera
while frontier:
if (time.time() - start_time) > MAX_EXECUTION_TIME:
return (time.time() - start_time, None)
# Scoatem boardul curent
s = heappop(frontier)
# Splutim board si cost
(cost,node) = s
#
cost_pana_nod = discovered[node][1]
# Testam daca s-a terminat
if node.r == end.r:
return (time.time() - start_time, len(discovered), len(node.moves))
# Mergem prin vecini
for v_node in get_neighbours(node):
cost_pana_la_vecin = cost_pana_nod + 1
if v_node not in discovered or cost_pana_la_vecin < discovered[v_node][1]:
discovered[v_node] = (node, cost_pana_la_vecin)
heappush(frontier, (cost_pana_la_vecin + h(v_node), v_node))
path = []
current_node = end
while current_node:
path.append(current_node)
current_node = discovered[current_node][0]
return (time.time() - start_time, len(path), len(path.moves))