Solve path problems with graphs

8 steps · about 4 h 20 min · Intermediate

  1. Model vertices and edges (guide, Wikipedia, 30 min)

    Translate entities and relationships into a graph with the right direction and labels.

  2. Choose an adjacency list (reference, Wikipedia, 25 min)

    Represent a sparse network compactly while keeping neighbour lookup straightforward.

  3. Define traversal state (guide, Wikipedia, 25 min)

    Track discovered and processed vertices so cycles do not cause repeated work.

  4. Traverse by distance layers (guide, Wikipedia, 35 min)

    Use a queue to visit an unweighted graph in increasing edge distance.

  5. Explore depth first (guide, Wikipedia, 35 min)

    Use recursion or a stack for reachability, components and structural exploration.

  6. Reconstruct an unweighted path (guide, Wikipedia, 30 min)

    Store predecessor links during breadth-first search and recover the route to a target.

  7. Recognise weighted paths (reference, Wikipedia, 35 min)

    Know when nonnegative edge costs require a priority-based algorithm instead of ordinary BFS.

  8. 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.