正加权图中查找最短路径--狄克斯特拉算法

步骤
1.找出最便宜的节点,即可再最短时间内前往的节点。
2.队以该节点的邻居,检查是否有前往他们的更短路径,如果有,就更新其开销。
3.重复这个过程,直到对图中的每个节点都这样做了。
4.计算最终路径。

image.png
#节点的所有邻居散列表
graph = {}
graph["start"] = {}
graph["start"]["a"] = 6
graph["start"]["b"] = 2
graph["a"] = {}
graph["a"]["fin"] = 1
graph["b"] = {}
graph["b"]["a"] = 3
graph["b"]["fin"] = 5
graph["fin"] = {}

#每个节点开销散列表
costs = {}
costs["a"] = 6
costs["b"] = 2
infinity = float("inf")
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]
    print(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)

你可能感兴趣的:(正加权图中查找最短路径--狄克斯特拉算法)