狄克斯特拉算法(入门)

来源:互联网 发布:同步带设计软件下载 编辑:程序博客网 时间:2024/06/05 14:11

狄克斯特拉算法可以找出加权图中前往X的最短路径。

注意:
- 其只适用于有向无环图
- 适用于正权边,负权边的将出错(贝尔曼—福德算法适用于负权边)

步骤:

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

实例:

这里写图片描述

# coding=utf-8# 图表graph = {}  graph["start"] = {}graph["start"]["a"] = 6  # 开始节点的邻居和邻居的开销graph["start"]["b"] = 2graph["a"] = {}  # a节点的邻居和邻居的开销graph["a"]["fin"] = 1  graph["b"] = {}  # b节点的邻居和邻居的开销graph["b"]["a"] = 3graph["b"]["fin"] = 5graph["fin"] = {}  # 终点的邻居和邻居的开销# 节点的开销散列表infinity = float("inf")costs = {}costs["a"] = 6  # 这时你可能找到更短的路径,但没有影响costs["b"] = 2   costs["fin"] = infinity#print infinity# 父节点的散列表parents = {}parents["a"] = "start"parents["b"] = "start"parents["fin"] = None# 处理过的节点列表processed = []# 查找开销最小的节点def find_lowest_cost_node(costs):    lowest_cost = float("inf")  # python中表示无穷大    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)  # 未处理的节点中找到开销最小的点print 'lowest_cost_node:',nodewhile 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 'lowest_cost_node:',nodeprint "Cost from the start to each node:"print 'parents:',parentsprint costs

结果:

=========== RESTART: C:\Users\LiLong\Desktop\Algorithm\dixstrah.py ===========lowest_cost_node: blowest_cost_node: alowest_cost_node: finlowest_cost_node: NoneCost from the start to each node:parents: {'a': 'b', 'b': 'start', 'fin': 'a'}{'a': 5, 'b': 2, 'fin': 6}>>> 

可以看出最短路径:

start2bstart3astart1fin

开销是:6


参考:《算法图解》—Aditya Bhargava
适合入门的看,讲的很基础,很多形象插图