python 使用Python heapq的Dijkstra算法,Coursera Stanford算法课程的解决方案:图形搜索,最短路径和数据结构

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 使用Python heapq的Dijkstra算法,Coursera Stanford算法课程的解决方案:图形搜索,最短路径和数据结构相关的知识,希望对你有一定的参考价值。

from heapq import heappush, heappop, heapify
def load_graph():
    with open('dijkstra.txt') as f:
        lines = f.readlines()
        head_set = []
        length_set = []
        for line in lines:
            edges = line.split()[1:]
            heads = []
            lengths = []
            for edge in edges:
                head, length = list(map(int, edge.split(',')))
                heads.append(head - 1)
                lengths.append(length)
            head_set.append(heads)
            length_set.append(lengths)
        return head_set, length_set
head_set, length_set = load_graph()
# tuples in (cost, head)
heap = [(0, 0)]
S = set()
Q = set([i for i in range(0, 200)])
d = [1000000 for i in range(0, 200)]
d[0] = 0
while len(Q) > 0:
    length, u = heappop(heap)
    if(u not in Q): continue
    Q.remove(u)
    S.add(u)
    for i, v in enumerate(head_set[u]):
        if v not in S:
            if d[v] > d[u]+ length_set[u][i]:
                d[v] = d[u] + length_set[u][i]
                heappush(heap, (d[v], v))
tmp = []
for i in [7,37,59,82,99,115,133,165,188,197]:
    tmp.append(d[i-1])
print(tmp)

以上是关于python 使用Python heapq的Dijkstra算法,Coursera Stanford算法课程的解决方案:图形搜索,最短路径和数据结构的主要内容,如果未能解决你的问题,请参考以下文章

python使用heapq快速查找最大或最小的 N 个元素

Python heapq模块

Python堆排序之heapq

python中使用heapq查看最大与最小的N个元素列表

python collection 和 heapq 模块使用说明

Python heapq 优先队列 Maxheap