SteelReed

Search

Search posts, questions…

Collections & DSAQuestion 21 / 25

Middle

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.

NoYes, non-negativeHas negativesFind shortest pathWeighted edges?BFS by layersO(V + E)Dijkstra + PriorityQueueO((V + E) log V)Bellman-Ford

3 points to say:

  1. Store sparse graphs as adjacency lists.
  2. Unweighted: BFS; positive weights: Dijkstra.
  3. 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.