迪克斯特拉算法


# -*- coding: utf-8 -*-


# the graph 绘制图
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"] = {}

# the costs table 成本表
infinity = float("inf")
costs = {}
costs["a"] = 6
costs["b"] = 2
costs["fin"] = infinity

# the parents table 父节点表
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循环就完成了。
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)

print("Cost from the start to each node:")
print(costs)

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