我正在开发一个使用Apacheage作为图形数据库的Python项目,我需要找到两个可能的 node 之间的最短路径.我如何使用Python实现这一点?创建 node 和图形 struct 的代码如下:

# Python code to create nodes and relationships
from age import Age

age = Age()
node_a = age.create_node("City", {"name": "New York"})
node_b = age.create_node("City", {"name": "Los Angeles"})
node_c = age.create_node("City", {"name": "Chicago"})
node_d = age.create_node("City", {"name": "Houston"})

edge_ab = age.create_edge(node_a, node_b, "CONNECTED", {"distance": 2451})
edge_ac = age.create_edge(node_a, node_c, "CONNECTED", {"distance": 713})
edge_cd = age.create_edge(node_c, node_d, "CONNECTED", {"distance": 940})
edge_bd = age.create_edge(node_b, node_d, "CONNECTED", {"distance": 1375})

# Sample graph structure:
# New York --(2451)-- Los Angeles
#     |                |
#   (713)            (1375)
#     |                |
#   Chicago --(940)-- Houston

我怎样才能找到从纽约到休斯顿的最短路由?

推荐答案

正如前面的答案中提到的,在ApacheAge中没有预定义的函数来寻找两个 node 之间的最短路径,但我们可以定义一个实现Dijkstra算法的Python函数来寻找图中 node 之间的最短路径.

以下是Dijkstra算法在Python语言中的实现:

import heapq

def dijkstra(age, start_node, end_node):
    # initialize distances and visited nodes
    distances = {start_node: 0}
    visited = set()
    heap = [(0, start_node)]

    # loop until all nodes are visited or destination node is found
    while heap:
        # get the node with the smallest distance
        (dist, current_node) = heapq.heappop(heap)

        # check if we have found the destination node
        if current_node == end_node:
            path = []
            while current_node in predecessors:
                path.append(current_node)
                current_node = predecessors[current_node]
            path.append(start_node)
            path.reverse()
            return path

        # check if we have already visited this node
        if current_node in visited:
            continue

        # add current node to visited set
        visited.add(current_node)

        # check neighbors of current node
        for neighbor_edge in current_node.get_edges_outgoing():
            neighbor_node = neighbor_edge.get_end_node()
            distance = dist + neighbor_edge.get_property("distance")

            # update distance to neighbor node if it's shorter than previous
            if neighbor_node not in distances or distance < distances[neighbor_node]:
                distances[neighbor_node] = distance
                heapq.heappush(heap, (distance, neighbor_node))

    # no path found
    return None

要使用该函数,可以传入age对象、startnode和end_node对象,它将返回它们之间的最短路径.

例如,要在问题中给出的图中找到纽约和休斯顿之间的最短路径,您可以这样调用函数:

start_node = node_a
end_node = node_d
shortest_path = dijkstra(age, start_node, end_node)
print(shortest_path)

Python相关问答推荐

使用mySQL的SQlalchemy过滤重叠时间段

. str.替换pandas.series的方法未按预期工作

为什么这个带有List输入的简单numba函数这么慢

管道冻结和管道卸载

用合并列替换现有列并重命名

"使用odbc_connect(raw)连接字符串登录失败;可用于pyodbc"

如何将一个动态分配的C数组转换为Numpy数组,并在C扩展模块中返回给Python

运输问题分支定界法&

SQLAlchemy Like ALL ORM analog

在ubuntu上安装dlib时出错

如何在turtle中不使用write()来绘制填充字母(例如OEG)

在matplotlib中删除子图之间的间隙_mosaic

找到相对于列表索引的当前最大值列表""

在Python中从嵌套的for循环中获取插值

在Python中控制列表中的数据步长

Python将一个列值分割成多个列,并保持其余列相同

如果不使用. to_list()[0],我如何从一个pandas DataFrame中获取一个值?

如何根据一定条件生成段id

在round函数中使用列值

来自任务调度程序的作为系统的Python文件