Grokking Algorithms



Yüklə 348,95 Kb.
Pdf görüntüsü
səhifə71/122
tarix05.12.2023
ölçüsü348,95 Kb.
#173611
1   ...   67   68   69   70   71   72   73   74   ...   122
grokking-algorithms-illustrated-programmers-curious

Chapter 7
 
 
I
 
 
Dijkstra’s algorithm
You found a shorter path to node A! Update the cost.
The new path goes through node B, so set B as the new parent.
Ok, you’re back at the top of the loop. The next neighbor 
for
is the 
Finish node.
How long does it take to get to the finish if you go through node B?
It takes 7 minutes. The previous cost was infinity minutes, and
7 minutes is less than that.


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:

Yüklə 348,95 Kb.

Dostları ilə paylaş:
1   ...   67   68   69   70   71   72   73   74   ...   122




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin