Shortest paths in practice
After this: Use heapq, PriorityQueue and graphlib, and know their limits.
On this page · 5 sections · 4 checks
You now know how Dijkstra's algorithm and topological order work. In real code, which parts do you write yourself, and which parts does your language give you?
Neither language has a graph type. Both have the heap that Dijkstra's algorithm needs. Python also has a ready-made topological sort.
What the libraries give you
| What you need | Python | Java |
|---|---|---|
| A min-heap of (distance, node) | heapq on a list of tuples | PriorityQueue with a comparator |
| Lowering an entry inside the heap | not available: push again and skip stale entries | not available: do the same |
| Topological order | graphlib.TopologicalSorter (Python 3.9 and later) | nothing built in: write Kahn's algorithm |
| A graph type | none: a dict of lists (networkx is outside the standard library) | none: a Map of Lists (JGraphT is outside the standard library) |
The second row has a name. Lowering the distance of an entry that is already inside a heap is called . Neither library offers it, so we use the method from Dijkstra in code: push a new entry and skip the old one when it comes out. That method is called .
The heap, with tuples
A tuple is a small group of values, such as (4, "B"). heapq compares tuples by their first value, and then by their second value. So (distance, node) pairs come out with the smallest distance first. Pushing the same node twice is allowed. Java's PriorityQueue needs a comparator that says the same thing.
import heapq
heap = []heapq.heappush(heap, (4, "B")) # pushed firstheapq.heappush(heap, (1, "C"))heapq.heappush(heap, (3, "B")) # a second entry for B: alloweddist, node = heapq.heappop(heap)print(dist, node)dist, node = heapq.heappop(heap)print(dist, node)record Entry(int dist, String node) {}PriorityQueue<Entry> heap = new PriorityQueue<>(Comparator.comparingInt(Entry::dist).thenComparing(Entry::node));heap.add(new Entry(4, "B")); // added firstheap.add(new Entry(1, "C"));heap.add(new Entry(3, "B")); // a second entry for B: allowedEntry e = heap.poll();System.out.println(e.dist() + " " + e.node());e = heap.poll();System.out.println(e.dist() + " " + e.node());Here is how to read it. There are three entries, and two of them are for B. The first pop gives the smallest distance, and the second pop gives the next smallest. The entry with distance 4 stays in the heap. In Dijkstra's algorithm, that is the stale entry that would be skipped later.
Topological order from the library
Python's graphlib.TopologicalSorter takes its input the other way round from our graphs. For each node, you give the nodes that it depends on. If there is a cycle, it raises a CycleError instead of returning a short order. Java has nothing built in, so you write the TopologicalOrder class from the last lesson.
from graphlib import TopologicalSorter, CycleError
# TopologicalSorter takes the edges the other way round: node -> what it depends ondepends_on = { "shower": ["wake"], "coffee": ["wake"], "dress": ["shower"], "leave": ["coffee", "dress"],}print(" -> ".join(TopologicalSorter(depends_on).static_order()))
try: list(TopologicalSorter({"a": ["b"], "b": ["a"]}).static_order())except CycleError as e: print("cycle:", e.args[1])wake -> shower -> coffee -> dress -> leave cycle: ['a', 'b', 'a']
// Java has no topological sorter in the standard library: reuse TopologicalOrder from the topological-order lesson.Map<String, List<String>> morning = new LinkedHashMap<>(); // neighbours listed alphabetically, as the visualizer doesmorning.put("wake", List.of("coffee", "shower"));morning.put("shower", List.of("dress"));morning.put("coffee", List.of("leave"));morning.put("dress", List.of("leave"));morning.put("leave", List.of());System.out.println(String.join(" -> ", TopologicalOrder.of(morning)));
Map<String, List<String>> cyclic = new LinkedHashMap<>();cyclic.put("a", List.of("b"));cyclic.put("b", List.of("a"));System.out.println(TopologicalOrder.of(cyclic) == null ? "cycle" : "order");wake -> coffee -> shower -> dress -> leave cycle
Here is how to read the Python version. depends_on says, for example, that leave depends on coffee and dress. static_order() gives back the nodes in a valid order. The second part builds a graph where a and b depend on each other, and it catches the CycleError. The Java version runs our own TopologicalOrder class on the same two graphs.
graphlib's order for the morning is wake, shower, coffee, dress, leave. It took shower before coffee, the opposite of the code in the last lesson. Both orders are valid.
Check yourself
You need a topological order. What does each standard library give you?
Three pushes, two pops.Three adds, two polls. What prints?
import heapq
heap = []heapq.heappush(heap, (4, "B")) # pushed firstheapq.heappush(heap, (1, "C"))heapq.heappush(heap, (3, "B")) # a second entry for B: alloweddist, node = heapq.heappop(heap)print(dist, node)dist, node = heapq.heappop(heap)print(dist, node)record Entry(int dist, String node) {}PriorityQueue<Entry> heap = new PriorityQueue<>(Comparator.comparingInt(Entry::dist).thenComparing(Entry::node));heap.add(new Entry(4, "B")); // added firstheap.add(new Entry(1, "C"));heap.add(new Entry(3, "B")); // a second entry for B: allowedEntry e = heap.poll();System.out.println(e.dist() + " " + e.node());e = heap.poll();System.out.println(e.dist() + " " + e.node());A build tool must run each task after the tasks it depends on. Which algorithm should it use, and what happens if two tasks depend on each other?
heapq and PriorityQueue have no decrease-key: you cannot lower the distance of an entry already in the heap. How does the lesson's code for Dijkstra's algorithm cope?
Connect
- Run Dijkstra's algorithm with heapq tuples or a PriorityQueue with a comparator, and skip stale entries, because neither has decrease-key.
- Use graphlib.TopologicalSorter in Python, and write Kahn's algorithm in Java.
- Pick BFS, Dijkstra's algorithm or topological order from the shape of the problem.