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'}