How do you store a graph, and why does BFS find the shortest path while DFS doesn't?
Short answer
BFS moves layer by layer of distance, so the first time it reaches a vertex is the fewest steps. DFS goes deep down one branch, so it does not guarantee the shortest. With weights, use Dijkstra.
3 points to say:
- Store sparse graphs as adjacency lists.
- Unweighted: BFS; positive weights: Dijkstra.
- DFS suits cycle finding and exploring whole branches.
Keep reading the deep dive
Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.