狄克斯特拉算法要点与python实现

使用情况

狄克斯特拉算法仅适用于有向无环图,且所有权重都是非负数。

算法步骤

  • 1、找到从权值最“便宜”的节点,即可在最短时间(路程、花费等)内前往的节点;
  • 2、对于该节点的邻居,检查是否有前往它们的更短路径,如果有,就更新其开销;
  • 3、重复上述过程,直到对图中的每个节点都这样处理;
  • 4、计算最终路径。

Python实现

# the graph
graph = {}  # 定义一个散列表
# 从起点开始,每一个节点又是一个散列表,存储与其相邻节点的权值
graph["start"] = {}
graph["start"]["a"] = 6
graph["start"]["b"] = 2
# 节点a与终点fin的权值
graph["a"] = {}
graph["a"]["fin"] = 1
# 节点b与其相邻节点的权值
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
# 父节点,对应于花费,比如costs["a"] = 6,a节点的上一个节点是start节点
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
    # Go through each node.
    for node in costs:  # 遍历整个图
        cost = costs[node]   #costs数组存储的是从起点到该node节点的花费
        # If it's the lowest cost so far and hasn't been processed yet...
        if cost < lowest_cost and node not in processed:  # 找到最小花费且没有被处理过的节点
            # ... set it as the new lowest-cost node.
            lowest_cost = cost
            lowest_cost_node = node
    return lowest_cost_node

# Find the lowest-cost node that you haven't processed yet.
node = find_lowest_cost_node(costs)
# If you've processed all the nodes, this while loop is done.
while node is not None:   # 如果没有找到花费最小的节点就会返回None
    cost = costs[node]
    # Go through all the neighbors of this node.
    neighbors = graph[node]  # 返回一个散列表,包含node节点的各个相邻节点
    for n in neighbors.keys():
        new_cost = cost + neighbors[n]  # 计算该节点的相邻节点新的花费:即该节点的花费+该节点到相邻节点的权值
        # If it's cheaper to get to this neighbor by going through this node...
        if costs[n] > new_cost:  # 如果之前的花费大于新的花费,更新花费和父节点
            # ... update the cost for this node.
            costs[n] = new_cost
            # This node becomes the new parent for this neighbor.
            parents[n] = node
    # Mark the node as processed.
    processed.append(node)  # 该节点已处理
    # Find the next node to process, and loop.
    node = find_lowest_cost_node(costs)  # 开始下一个未处理节点
print("Cost from the start to each node:")
print(costs)


发布了96 篇原创文章 · 获赞 19 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Thera_qing/article/details/104342624