Dijkstra’s algorithm-Python代码实现

本文介绍了使用Python实现Dijkstra's算法的过程,包括保存在哈希表中、寻找最短路径以及展示算法结果。
摘要由CSDN通过智能技术生成

Saving in Hash Table

graph = {}
#因为里面嵌套太多hash table所以不从start开始,把start作为parent的node的距离作为其本身cost

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
parent = {}
parent['A'] = 'Start'
parent['B'] = 'Start'
parent['Fin'] = None
processed = []

Finding minimum path

def find_min_cost_node(costs):
  lowest_cost = infinity
  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

Dijkstra’s algorithm

node = find_min_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
      parent[n] = node
  processed.append(node)
  node = find_min_cost_node(costs)     

Results

print('The shortest distance is {}'.format(costs['Fin']))
print('The shortest path is {}'.format(parent))

Out:

The shortest distance is 6
The shortest path is {'A': 'B', 'B': 'Start', 'Fin': 'A'}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值