Python实现迪杰斯特拉算法

不能解决环问题和负加权问题!
贝尔曼福特算法有待研究

graph = {}# 图
graph["you"] = ["alice","bob","claire"] #一层图
graph["start"] ={} #用来表示权重
graph["start"]["a"] = 6 # graph["start"] 是一个散列表
graph["start"]["b"] = 2
graph["start"].keys() # 此散列表的所有邻居  是a和b
graph["a"] = {}
graph["a"]["fin"]=1
graph["b"] = {}
graph["b"]["a"] = 3
graph["b"]["fin"] = 5
graph["fin"] = {}
#创建开销表
infinity = float("inf")
costs = {}
costs["a"] = 6
costs["b"] = 2
costs["fin"] = infinity
#存储父节点的散列表
parents={}
parents["a"] = "start"
parents["b"] = "start"
parents["fin"] = None
#已经处理过的节点
processed = []
#找出开销最小的节点
def find_lowest_cost_node(costs):
    lowest_cost = float("inf")
    lowest_cost_node = None
    for node in costs:
        cost = costs[node]
        if cost < lowest_cost and node not in processed:
            lowest_cost = cost
            lowest_cost_node = node
    return lowest_cost_node
#在未处理的节点中找出开销最小的节点
node = find_lowest_cost_node(costs)
while node is not None:
    cost = costs[node]                  #获取这个开销最小的节点的开销
    neighbors = graph[node]             #以及其邻居
    for n in neighbors.keys():          #遍历邻居
        new_cost = cost+neighbors[n]    #起点->开销最小的->邻居
        if costs[n] > new_cost:         #新旧开销的对比 原来的开销和 上面计算的开销
            costs[n] = new_cost         #经过节点前往邻居 和直接前往邻居之间的最小的开销
            parents[n] = node           #新路径经过开销最小的节点 这个节点更新为邻居的父节点
    processed.append(node)
    node = find_lowest_cost_node(costs)

你可能感兴趣的:(Python实现迪杰斯特拉算法)