Tiem Cong Nghe

Showing suggestions.

Opening the store's index…
↑↓ to move↵ to openesc to close
Tiem Cong Nghe search

Free explainer · Video · Code · Quiz

Graph Traversal: BFS and DFS

Visit every vertex of a graph reachable from a starting point. BFS uses a queue and walks level by level; DFS uses a stack and dives deep first. Same code shape, one different container, and why that changes everything.

Difficulty
Easy
Time
O(V + E)
Space
O(V + E)

Try it yourself

Step through it at your own pace — this is Graph Traversal Animation, running right on the page.

Get this code

LiveGraph Traversal Animation

Loading the preview…

How it works

The idea, a worked example, and the traps to avoid.

The idea

You are in a maze of rooms joined by doors, and you want to visit every room you can reach without going in circles. You need two things: a way to remember which rooms you have already seen, and a list of rooms you have found but not entered yet. Graph traversal is exactly that, and the whole difference between the two classic versions is how you treat that list.

  • Breadth-first search (BFS) takes the oldest room on the list. The list is a queue: first in, first out. You see everything one door away, then everything two doors away, then three. It spreads like a ripple on water.
  • Depth-first search (DFS) takes the newest room on the list. The list is a stack: last in, first out. You walk through one door after another until you hit a dead end, then back up to the last room that still had an unexplored door.

Swap the queue for a stack and BFS becomes DFS. Nothing else changes.

The graph comes as an adjacency list: graph[u] lists the neighbours of vertex u. Both functions return the vertices in the order they were visited. To make the order the same in every language, neighbours are always tried in the order graph[u] lists them.

Walkthrough

An undirected graph with vertices A to F (the code uses 0 to 5). Edges: A–B, A–C, B–D, C–D, D–E, C–F. Written as lists, in this order:

Vertex Neighbours
A B, C
B A, D
C A, D, F
D B, C, E
E D
F C

BFS from A. The queue starts as [A].

Step Take out New in the queue Queue after
1 A B, C B, C
2 B D (A is seen) C, D
3 C F (A and D are seen) D, F
4 D E F, E
5 F none E
6 E none empty

Order: A B C D F E. By level: A is 0 edges from the start, B and C are 1, D and F are 2, E is 3. A BFS order never goes back a level.

DFS from A. The stack starts as [A] (the top is on the right). To visit the first neighbour first, the code pushes neighbours last to first.

Step Take off Pushed Stack after
1 A C, B C, B
2 B D C, D
3 D E, C C, E, C
4 C F C, E, F
5 F none C, E
6 E none C
7 C stale: already visited, skipped empty

Order: A B D C F E. From A it went to B, from B to D, and from D it chose C (listed before E) and went down to F before it ever came back for E. Look at step 3: C went onto the stack for the second time, and the old copy at the bottom was thrown away in step 7. That leads to the next idea.

Marking visited: on push or on pop?

A vertex must never be processed twice, or a cycle would make you loop forever. The question is when to mark it. The listings choose differently for each search, and both choices have a reason.

BFS marks when it pushes. The moment you discover a vertex, you know its level: it is one more than the vertex that found it, and nobody can find it earlier. So mark it right then, and it enters the queue at most once. The queue never holds more than V entries, and distance to the start is settled at the moment of discovery.

The other way, marking when taking out, still produces the same order for BFS. But a vertex can wait in the queue several times (D is reachable from B and from C), and you need a stale check on the way out. It works, it just wastes space.

DFS marks when it pops. Here the order of marking matters, not just the waste. The newest entry on the stack is the one that should win. In the walkthrough, C was pushed by A, and again later by D. D's copy sits on top and is taken first, which is exactly what a recursive DFS does: from D, go to C. If you marked C on the first push, the later push would be refused, C would stay buried under E, and the stack would take E first. That gives A B D E C F: still a valid walk, but no longer a depth-first one, because from D it jumped to E although C was listed first. The price of marking on pop is the stale entries you skip, like the C at the bottom.

A rule of thumb: BFS wants the first time a vertex is seen, DFS wants the last.

Why the neighbours are pushed backwards

A stack hands back the last item pushed first. Push the neighbours in listed order and the last neighbour would be explored first: for a star where graph[0] is [1, 2, 3], that gives 0 3 2 1. Pushing them last to first puts the first neighbour on top, so dfs returns 0 1 2 3, the same order a recursive DFS gives. That is the documented rule of this page: neighbours are tried in the order graph[u] lists them, in both searches.

It also means the output depends on the list order, not only on the graph. Reorder graph[0] to [3, 1, 2] and both BFS and DFS visit 3 first. If you build lists from an edge list, say in which order you fill them, or sort them.

Disconnected graphs, cycles, self-loops

  • Disconnected. Both searches only reach the part of the graph connected to start. On a graph with parts {0, 1, 2} and {3, 4, 5}, starting at 3 returns just 3 4 5. To cover everything, loop over all vertices and start a search from each one you have not visited yet. Each start discovers one connected component, so counting those starts counts the components.
  • Cycles. The visited array is the only thing that stops you walking a cycle forever. Without it, 0 → 1 → 2 → 0 never ends.
  • Self-loops and repeated edges. 0 → 0 is just a neighbour that is already visited, so it is skipped. Repeated edges work the same way. No special code needed.
  • Directed graphs. The same code works if graph[u] only lists the vertices u points to. Then "reachable" means reachable by following arrows, so a vertex can exist but never be found from start.
  • Isolated start. A start with no neighbours returns just [start].

Complexity

Each vertex is visited once and each edge is looked at once from each end (twice in an undirected graph, so a constant factor), so the time is O(V + E).

Space is the visited array plus the order and the container: O(V) for BFS, because marking on push means each vertex is queued once. DFS marks on pop, so a vertex can sit on the stack once per edge that leads to it. In a complete graph on 5 vertices (10 edges), dfs from 0 pushes 11 entries, skips 6 stale ones, and the stack reaches 7 entries even though there are only 5 vertices. In the worst case the stack holds O(E) entries, which is why this page says O(V + E) for space. A DFS that remembers which neighbour it tried last for each vertex stays in O(V), but it needs more bookkeeping than this listing.

Common bugs

  • Marking too late in BFS and forgetting the stale check. The same vertex is processed several times, and the order contains duplicates.
  • Marking too early in DFS, as above. The traversal still touches every vertex, so a test that only checks the set of vertices passes. Only the order is wrong.
  • Using shift() for a queue in JavaScript. It can cost O(n) per call, so a big graph may turn O(V + E) into O(V²). The listing keeps a head index instead.
  • Recursive DFS on a deep graph. A path of 100,000 vertices overflows the call stack in most languages. The explicit stack does not.
  • Forgetting the other direction when building an undirected graph. If you add u → v but not v → u, you have a directed graph.
  • Expecting BFS or DFS to find weighted shortest paths. BFS counts edges, not weights. For weights, use Dijkstra.

When to use which

BFS when you want the fewest edges: shortest path in an unweighted graph, minimum moves in a puzzle, degrees of separation, the nearest exit in a grid, level-by-level processing. Remember dist[v] = dist[u] + 1 for each new vertex, and BFS becomes a shortest-hop calculator.

DFS when you need to explore everything along a path or the structure of the graph: finding a path, connected components, cycle detection, topological sort, solving a maze, backtracking. DFS uses less memory on wide graphs, where BFS's queue holds a whole level.

If you only need "can I reach X?", either works.

Interview variations

  1. Shortest path in an unweighted graph, or a grid. BFS with a distance per vertex, or one BFS level at a time. A grid is a graph where each cell has up to four neighbours.
  2. Number of islands / connected components. Loop over all vertices, start a DFS or BFS from each unvisited one, and count the starts.
  3. Detect a cycle. In an undirected graph, a neighbour that is already visited and is not the vertex you just came from means a cycle. In a directed graph you also need to know which vertices are still on the current path.
  4. Is the graph bipartite? BFS and give every vertex the opposite colour of the one that found it. If you meet a neighbour with the same colour, the answer is no.
  5. Word ladder. Every word is a vertex, two words are neighbours if they differ by one letter, and BFS from the start word gives the shortest ladder.

Code

The same algorithm, step for step, in 4 languages.

JavaScript
// Breadth-first and depth-first search on an unweighted graph.
// Both visit every vertex reachable from `start` exactly once and return the order they did it in.
// The only difference is the container for the vertices still waiting: a queue (first in, first out)
// walks the graph level by level, a stack (last in, first out) dives as deep as it can before backing up.
// Neighbours are always tried in the order graph[u] lists them, so every language prints the same thing.

/**
 * Breadth-first search: all vertices one edge from `start`, then two edges away, then three...
 * A vertex is marked when it goes into the queue, so it is queued at most once.
 *
 * @param {number[][]} graph adjacency list: graph[u] lists the neighbours of vertex u, in the order to try them
 * @param {number} start the vertex to begin at, 0 <= start < graph.length
 * @returns {number[]} the vertices reachable from `start`, in the order they were visited
 */
export function bfs(graph, start) {
  const visited = new Array(graph.length).fill(false);
  const order = [];
  const queue = [start];
  let head = 0; // queue[head] is the front; everything before it has already been taken out
  visited[start] = true;

  while (head < queue.length) {
    const u = queue[head];
    head++;
    order.push(u);
    for (const v of graph[u]) {
      if (visited[v]) continue;
      visited[v] = true; // marked now, not when taken out, so v can never be queued twice
      queue.push(v);
    }
  }
  return order;
}

/**
 * Depth-first search with an explicit stack: follow one path as far as it goes, then back up.
 * A vertex is marked when it comes OFF the stack. The visit order is exactly the one a recursive
 * search gives, trying graph[u] from first neighbour to last.
 *
 * @param {number[][]} graph adjacency list: graph[u] lists the neighbours of vertex u, in the order to try them
 * @param {number} start the vertex to begin at, 0 <= start < graph.length
 * @returns {number[]} the vertices reachable from `start`, in the order they were visited
 */
export function dfs(graph, start) {
  const visited = new Array(graph.length).fill(false);
  const order = [];
  const stack = [start];

  while (stack.length > 0) {
    const u = stack.pop();
    // Stale entry: u was pushed twice and its other copy was already taken. Skip it.
    if (visited[u]) continue;
    visited[u] = true;
    order.push(u);
    // Push the neighbours last to first, so the first one ends on top and is taken next.
    for (let i = graph[u].length - 1; i >= 0; i--) {
      const v = graph[u][i];
      if (visited[v]) continue;
      stack.push(v);
    }
  }
  return order;
}

Test yourself

10 quick questions to check it stuck.

Q1 · An undirected graph has 6 vertices, with these adjacency lists: 0: [1, 2], 1: [0, 3], 2: [0, 3, 5], 3: [1, 2, 4], 4: [3], 5: [2]. What does bfs(graph, 0) return?

Take the quiz

Take it further

  • Animation

    Graph Traversal Animation

    Queue or stack, watch the search choose: BFS and DFS on a glowing graph, side by side, ready for your lessons, slides and posts

    Free