Graphs
Edges connect vertices that may have multiple routes between them. Traversal needs an explicit policy for visiting each vertex.
Picture the idea
Metro stations form vertices and routes form edges. Fewest stops and shortest travel time can produce different journeys.
When to use it
Represent reachability, precedence, connections or path costs. First determine direction and edge weights.
How it works
BFS processes one distance layer at a time by queue. Dijkstra repeatedly settles the smallest tentative distance when edge weights are nonnegative.
- Enumerate neighbors from an adjacency list.
- Mark a vertex on discovery.
- Relax an edge if a cheaper route appears.
- Union components when a forest edge is accepted.
BFS and DFS take O(V + E) on adjacency lists. Binary-heap Dijkstra takes O((V + E) log V) for a simple graph.
Watch for this mistake
The first path DFS finds can be longer than another route. BFS shortest edge counts require equal edge costs.
State how you handle disconnected components, repeated edges and isolated vertices.