[英]Optimize graph for path finding and getting nodes at specific coordinates
我正在构建一个图表 class 表示为一个字典。 图 class 用于在大型 2D 网格矩阵上执行路径查找。 节点存储为键,相邻节点存储为值。
这对于快速路径搜索很有效,但我还需要从由它们的 x 和 y 坐标确定的 dict 中获取特定节点。
class Node(object):
def __init__(self, x, y):
self.x = x
self.y = y
class Graph(dict):
def get_node_at(self, x, y):
for node in self:
if node.x == x and node.y == y:
return node
def set_neighbours(self):
pass
graph = Graph()
# build a 2d matrix of nodes
for x in range(10):
for y in range(10):
graph[Node(x,y)] = []
# set the neighbour nodes for each node
graph.set_neighbours()
mynode = graph.get_node_at(6,6) # will later be executed quite often
有没有办法优化图 class 以便 get_node_at 方法在大网格上表现更好?
向Graph
添加一个类似于{(x,y):node}
的索引。 这将需要实现__setitem__
以将Node
添加到索引中,如果另一个Node
已经存在则将其删除,并且__delitem__
也会从索引中删除该Node
。 这将允许get_node_at(self, x, y)
只return self.index[(x,y)]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.