-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patha_star.py
62 lines (49 loc) · 1.84 KB
/
a_star.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
import heapq
import geometry
class PriorityQueue:
def __init__(self):
self.elements = []
def empty(self):
return len(self.elements) == 0
def put(self, item, priority):
heapq.heappush(self.elements, (priority, item))
def get(self):
return heapq.heappop(self.elements)[1]
class node:
def __init__(self):
self.hScore = 0
self.stepCost = 0
self.fScore = 0
self.childIndexes = []
self.index = -1
self.camerasState = [True]*geometry.Gallery.camerasAmount
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.fScore == other.fScore
return NotImplemented
def __lt__(self, other):
if isinstance(other, self.__class__):
return self.fScore< other.fScore
def expand(self):
(self.childIndexes,self.hScore) = geometry.getIndexOfCamerasToTurnOff(self.camerasState,self.index)
self.fScore = self.stepCost + self.hScore
def aStar(cameras):
root = node()
if not geometry.isGalleryCovered(root.camerasState):
return None
root.expand()
nodesQueueByFScore = PriorityQueue()
nodesQueueByFScore.put(root,-root.fScore*1000 - root.stepCost)
while not nodesQueueByFScore.empty():
currentNode = nodesQueueByFScore.get()
if currentNode.hScore == 0:
return currentNode
for (i,childIndex) in enumerate(currentNode.childIndexes):
newNode = node()
newNode.stepCost = currentNode.stepCost + 1
newNode.childIndexes = childIndex
newNode.index = childIndex
newNode.camerasState = list(currentNode.camerasState)
newNode.camerasState[childIndex] = False
newNode.expand()
nodesQueueByFScore.put(newNode,-newNode.fScore*1000 - newNode.stepCost)