Solve path problems with graphs
8 steps · about 4 h 20 min · Intermediate
- Model vertices and edges (guide, Wikipedia, 30 min)
Translate entities and relationships into a graph with the right direction and labels.
- Choose an adjacency list (reference, Wikipedia, 25 min)
Represent a sparse network compactly while keeping neighbour lookup straightforward.
- Define traversal state (guide, Wikipedia, 25 min)
Track discovered and processed vertices so cycles do not cause repeated work.
- Traverse by distance layers (guide, Wikipedia, 35 min)
Use a queue to visit an unweighted graph in increasing edge distance.
- Explore depth first (guide, Wikipedia, 35 min)
Use recursion or a stack for reachability, components and structural exploration.
- Reconstruct an unweighted path (guide, Wikipedia, 30 min)
Store predecessor links during breadth-first search and recover the route to a target.
- Recognise weighted paths (reference, Wikipedia, 35 min)
Know when nonnegative edge costs require a priority-based algorithm instead of ordinary BFS.
- Test the model on a real network (interactive, NetworkX documentation, 45 min)
Build a small graph, compare traversals and verify the returned path with a maintained graph library.