我正在尝试实施AStar搜索算法,但我无法从边缘删除元素(打开列表)。我像这样推送Cells
:
heapq.heappush(myHeap, (priority, cell)
我的细胞类看起来像这样:
class Cell(object):
def __init__(self, x, y):
self.X = int(x)
self.Y = int(y)
self.G = float("inf")
self.parent = None
def __lt__(self, other):
return (self.X, self.Y) < (other.X, other.Y)
def __eq__(self, other):
return int(self.X) == int(other.X) and int(self.Y) == int(other.Y)
有没有办法我可以heapq.remove(cell)
或heapq.heappop(cell)
从堆中删除条目然后重新合并它?
目前,我这样做,但我不认为它正常工作,因为我有时会无限循环:
def remove(self, item):
index = 0
for i in range(len(myHeap)):
if(myHeap[i][1] == item):
index = i
# Move slot to be removed to top of heap
while index > 0:
up = int((index + 1) / 2 - 1)
self.heap[index] = self.heap[up]
index = up
# Remove top of heap and restore heap property
heapq.heappop(myHeap)
任何帮助都将不胜感激。
答案 0 :(得分:0)
您也可以在列表myHeap
上使用常规列表方法。因此,首先从列表中删除一些特定元素,然后堆积并推送具有新优先级的元素:
myHeap.remove((priority, cell))
heapq.heapify(myHeap)
heapq.heappush(myHeap, (new_priority, cell))