# 算法笔记7----狄克斯特拉算法

7.1使用狄克斯特拉算法

（1）找出最便宜的节点，即可在最短时间内前往的节点。

（2）对于该节点的邻居，检查是否有前往它们更短的路径，如果有，就更新其开销。

（3）重复这个过程，直到对图中的每个节点都这样做了。

（4）计算最终路径。

7.2术语

7.4负权边

7.5实现

graph = {}
graph['you'] = ['alice', 'bob', 'claire']
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'] = {}
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)

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

7.6小结

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120