迪克斯特拉算法原理与Python实现

原理
  1. 找到距离源点src距离最近的点,这个最短距离就是该点的最短距离
  2. 对这个点的邻居节点做松弛操作:检测这个点是否可以作为它的邻居的最短路径上面的点,如果可以则更新
实现
def f(G, nodes, src):
    dist = {}
    MAX_INT = 99999999999
    node_pre = {}
    for node in nodes:
        dist[node] = MAX_INT
        node_pre[node] = src
    dist[src] = 0
    T = nodes[:]
    while len(T)>0:
        min_dist = MAX_INT
        min_node = -1
        for node in T:
            if dist[node] < min_dist:
                min_dist = dist[node]
                min_node = node
        T.remove(min_node)
        # 松弛
        neigs = G[min_node]
        for neig in neigs:
            # dist[neig] = min(dist[neig], dist[min_node]+G[min_node][neig])
            if dist[min_node]+G[min_node][neig] < dist[neig]:
                node_pre[neig] = min_node
                dist[neig] = dist[min_node]+G[min_node][neig]

    # 根据前驱节点,逆向出路径
    paths = {}
    for node in dist:
        paths[node] = [node]
        tmp = node
        while True:
            pre = node_pre[tmp]
            paths[node].append(pre)
            if pre==src:
                break
            else:
                tmp = pre
        paths[node] = paths[node][::-1]
    return dist, paths


if __name__ == '__main__':
    G = {}
    G['A'] = {'B': 7, 'D': 2}
    G['B'] = {'A': 7, 'C': 3}
    G['C'] = {'B': 3, 'D': 1, 'E': 3}
    G['D'] = {'A': 2, 'C': 1, 'E': 1, 'G': 2}
    G['E'] = {'C': 3, 'D': 1, 'F': 4}
    G['F'] = {'E': 4, 'H': 1}
    G['G'] = {'D': 2, 'H': 1}
    G['H'] = {'G': 1, 'F': 1}
    nodes = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
    src = 'A'
    dist, paths = f(G, nodes, src)
    print(dist)
    for node in paths:
        print(paths[node])

案例如图所示:
迪克斯特拉算法原理与Python实现_第1张图片

结果如图所示:
迪克斯特拉算法原理与Python实现_第2张图片

后续将利用队列进行优化,请持续关注。

你可能感兴趣的:(算法OJ,算法)