📜  门| GATE-CS-2004 |问题3(1)

📅  最后修改于: 2023-12-03 15:28:42.333000             🧑  作者: Mango

GATE-CS-2004 Problem 3

该问题要求计算一个无向图的最短路径。我们可以使用 Dijkstra 算法来解决这个问题。Dijkstra算法是一种贪心算法,要求每次选择当前离源点最近的顶点,并且更新其相邻顶点的距离。直到所有的顶点都被遍历过,最终得到源点到每个顶点的最短距离。下面是 Dijkstra 算法的伪代码:

1. Create a set sptSet (shortest path tree set) that keeps track of vertices included in shortest path tree, whose minimum distance from source is calculated and finalized.
2. Assign a distance value to all vertices in the input graph. Initialize all distance values as INFINITE. Assign distance value as 0 for the source vertex so that it is picked first.
3. While sptSet doesn't include all vertices:
    a) Pick a vertex u which is not in sptSet and has minimum distance value.
    b) Include u to sptSet.
    c) Update distance value of all adjacent vertices of u. To update the distance values, iterate through all adjacent vertices. For every adjacent vertex v, if sum of distance value of u (from source) and weight of edge u-v, is less than the distance value of v, then update the distance value of v.

现在我们来看一下如何把它转化为 Python 代码:

import heapq


def dijkstra(graph, src):
    dist = {v: float('inf') for v in graph}
    dist[src] = 0
    pq = [(0, src)]
    while pq:
        cost, u = heapq.heappop(pq)
        if cost > dist[u]:
            continue
        for v, weight in graph[u].items():
            alt = cost + weight
            if alt < dist[v]:
                dist[v] = alt
                heapq.heappush(pq, (alt, v))
    return dist

这里用了 Python 的 heapq 模块来实现优先队列,来不断保存当前所有可达的最短距离。

最后,在主程序中调用这个函数,给定一个图形的数据结构表示,然后计算源节点和目标节点之间的最短距离。

graph = {
    'A': {'B': 1, 'C': 4},
    'B': {'A': 1, 'C': 2, 'D': 5},
    'C': {'A': 4, 'B': 2, 'D': 1},
    'D': {'B': 5, 'C': 1}
}

src_node = 'A'
dest_node = 'D'
shortest_path = dijkstra(graph, src_node)[dest_node]
print(f"The shortest path from {src_node} to {dest_node} is {shortest_path}.")

这里的图形数据结构使用了字典,其中键为节点,值为另一个字典,该字典包含所有可达该节点的节点及其权重。在此示例中,节点 A 具有两个可达的节点 B 和 C,分别具有权重 1 和 4。