Traversal Techniques (BFS & DFS)

easy

Given an undirected graph with V vertices (labelled 0 .. V-1) and an edge list edges, return its BFS and DFS traversals as a two-row array: row 0 is the breadth-first order, row 1 is the depth-first order.

Start both from vertex 0 and, at every vertex, visit its neighbours in increasing order. If the graph is disconnected, continue from the smallest unvisited vertex so every vertex appears.

Hints

Convert the edge list into a sorted adjacency list first.
BFS uses a queue and marks visited on enqueue; DFS uses recursion or a stack.
Restart the traversal from the smallest unvisited vertex to handle disconnected graphs.

Common doubts

So the traversal order is deterministic — ties between neighbours are broken by smallest label.
Otherwise the same vertex can be enqueued by several neighbours before it's processed, inflating work and possibly the order.
The iterative version pushes neighbours in reverse and marks a vertex when it's popped, which reproduces the recursive preorder.

Interview follow-ups

On an unweighted graph, the BFS level at which a vertex is first reached is its distance from the source.
For connectivity, cycle detection, and ordering (topological sort) — anything that needs the deep structure rather than distances.

Fun facts

  • BFS and DFS differ only by swapping a queue for a stack — the rest of the code is identical.
  • Every problem in this module is one of these two walks plus a little bookkeeping.

Asked at

AmazonMicrosoftGoogle
Frequently Sometimes Occasionally
Example 1
Input: V = 5, edges = [[0,1],[0,2],[1,3],[2,4]]
Output: [[0,1,2,3,4],[0,1,3,2,4]]
BFS explores in rings from 0; DFS goes deep down 0-1-3 then 0-2-4.
Example 2
Input: V = 5, edges = [[0,1],[2,3]]
Output: [[0,1,2,3,4],[0,1,2,3,4]]
Disconnected: after component {0,1}, restart at 2, then the isolated 4.
Constraints

- 1 <= V <= 10^4 - 0 <= edges.length <= V*(V-1)/2 - 0 <= u, v < V - u != v - no duplicate edges

Solve this problem →