137
Implementation
Set the new cost and the new parent for the Finish node.
Ok, you updated the costs for all the neighbors of node B.
Mark it as
processed.
Find the next node to process.
Get the cost and neighbors for node A.
138
Chapter 7
I
Dijkstra’s algorithm
Node A only has one neighbor: the Finish node.
Currently it takes 7 minutes to get to the Finish node.
How long would
it take to get there if you went through node A?
It’s faster to get to Finish from node A! Let’s update the cost
and parent.
139
Implementation
If it’s the lowest cost
so far and hasn’t been
processed yet …
def find_lowest_cost_node(costs):
lowest_cost = float(“inf”)
lowest_cost_node = None
for node in costs:
Go through each node.
cost = costs[node]
if cost < lowest_cost and node not in processed:
lowest_cost = cost
… set it as the new lowest-cost node.
lowest_cost_node = node
return lowest_cost_node
Once you’ve processed all the nodes, the algorithm is over.
I hope
the walkthrough helped you understand the algorithm a little better.
Finding the lowest-cost node is pretty easy with the
find_lowest_
cost_node
function. Here it is in code:
Dostları ilə paylaş: