book-notes

Chapter 7 - Dijkstra’s algorithm

Working with Dijkstra’s algorithm

Untitled

Untitled

Untitled

  1. Find the cheapest node. This is the node you can get to in the least amount of time.
  2. Check whether there’s a cheaper path to the neighbors of this node. If so, update their costs.
  3. Repeat until you’ve done this for every node in the graph.
  4. Calculate the final path.
    • Python implementation
     # Find the lowest cost node that you haven't processed yet
     node = find_lowest_cost_node(costs)
        
     # If you've processed all the nodes, the while loop is done
     while node is not None:
        
     	# Get the cost and neighbors of current node
     	cost = costs[node]
     	neighbors = graph[node]
        
     	# Loop through the neighbors
     	for n in neighbors.keys():
     		new_cost = cost + neighbors[n]
        
     		# If it's cheaper to get to the neighbor by going through current node,
     		# update the cost for the neighbor
     		if costs[n] > new_cost:
     			costs[n] = new_cost
     			parents[n] = node
        
     	# Mark the node as processed
     	processed.append(node)
        
     	# Find the next node to process
     	node = find_lowest_cost_node(costs)
    

Terminology

Untitled

Negative-weight edges

Recap

Notes: https://medium.com/basecs/finding-the-shortest-path-with-a-little-help-from-dijkstra-613149fbdc8e