Dijkstra’s Graph Algorithm with Python

In the previous articles, we have presented graphs with BFS and DFS. The BFS is actually good to find the path with the fewest nodes. But if the path with the fewest nodes is actually the most expensive, then we face a problem. Imagine a flight with 1 stop that actually costs $500 vs a direct flight that costs $2000. BFS will pick the direct flight ever time, regardless of the price.

To solve that problem and to take the price (or the distance, or any other weight) we need Dijkstra’s Algorithm.

The shortest path with weights is A>C>G>H>P

Dijkstra is actually similar to BFS, but with a major upgrade: it uses a Priority Queue. Instead of exploring the next node in line, it always explores teh cheapest node available anywhere in the graph. Here is the implementation in Python, with heapq. Notice that we track cost_so_far to ensure we never do more work than necessary:

Additionally, we have introduced a “Lazy Visualization Trick”, that uses the graph visualization function, presented in a previous article. The idea is to fix the input, without changing the function. Thus, once we have the path (in our case ['A', 'C', 'G', 'H', 'P'], we write a tiny function that takes our raw text data and “stars” the names of the nodes in our path like that:

  • A becomes *A*
  • C becomes *C*

When we feed this modified text back into our original plotting function, it treats *A* as a new name and displays it with the stars. It is simple, visual way to debug your algorithm without wirting a new visualization engine from scratch.

Check out the video and the code in GitHub:

Enjoy it!
🏁😺🌞

Tagged with: , , , ,