astar_path#
- astar_path(G, source, target, heuristic=None, weight='weight')[源代码]#
使用a*(a-star)算法返回源和目标之间最短路径中的节点列表。
可能有多条最短路径。这只返回一个。
- 参数
- G网络X图表
- source结点
路径的起始节点
- target结点
路径的结束节点
- heuristic功能
用于评估从a节点到目标的距离估计的函数。该函数接受两个节点参数,并且必须返回一个数字。
- weight字符串或函数
如果这是一个字符串,则边权重将通过具有此关键字的边属性(即边连接的权重)进行访问
u
至v
将会是G.edges[u, v][weight]
)。如果不存在这样的边属性,则假定边的权重为1。如果这是一个函数,则边的权重是该函数返回的值。该函数必须恰好接受三个位置参数:一条边的两个端点和该边的边属性字典。该函数必须返回一个数字。
- 加薪
- NetworkXNoPath
如果在源和目标之间没有路径存在。
参见
shortest_path
,dijkstra_path
实例
>>> G = nx.path_graph(5) >>> print(nx.astar_path(G, 0, 4)) [0, 1, 2, 3, 4] >>> G = nx.grid_graph(dim=[3, 3]) # nodes are two-tuples (x,y) >>> nx.set_edge_attributes(G, {e: e[1][0] * 2 for e in G.edges()}, "cost") >>> def dist(a, b): ... (x1, y1) = a ... (x2, y2) = b ... return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5 >>> print(nx.astar_path(G, (0, 0), (2, 2), heuristic=dist, weight="cost")) [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)]