This repository was archived by the owner on May 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpriorityqueue.py
More file actions
72 lines (56 loc) · 1.54 KB
/
Copy pathpriorityqueue.py
File metadata and controls
72 lines (56 loc) · 1.54 KB
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
class PriorityQueue:
"""
A data structure acting as a priority queue for the open list.
It uses a 2D hash table.
1. The first layer uses the `value` as a key.
2. The second layer uses the `grid` as a key.
"""
def __init__(self, val):
"""
`val` us a function that converts the objects in this priority queue into numbers.
For example, the function can be a heuristic.
"""
self.val = val
self.length = 0
self.hash = {}
def insert(self, obj:object):
if self.hash.get(self.val(obj)) is None:
self.hash[self.val(obj)] = {}
self.hash[self.val(obj)][str(obj)] = obj
self.length += 1
def getMin(self):
if self.isEmpty():
return None
# Finding minimum cost in first layer.
minVal = None
for key in self.hash.keys():
if minVal is None:
minVal = key
if key < minVal:
minVal = key
# Returning random first value with min cost.
minHash = self.hash[minVal]
for min in minHash.values():
return min
def removeMin(self):
if self.isEmpty():
return None
min = self.getMin()
# Removing the value from the secondary hash.
self.hash[self.val(min)].pop(str(min))
# Removing the secondary hash if it is empty.
if len(self.hash[self.val(min)]) == 0:
self.hash.pop(self.val(min))
self.length -= 1
return min
def getValue(self, obj):
if self.isEmpty():
return None
costHash = self.hash.get(self.val(obj))
if costHash is None:
return None
return costHash.get(str(obj))
def updateValue(self, obj):
self.hash[self.val(obj)][str(obj)] = obj
def isEmpty(self):
return self.length == 0