Skip to content

Graphs: BFS & DFS

A queue explores in rings; a stack explores down a corridor. Both need a visited set

1. What a graph is

A graph is a set of vertices and a set of edges. Edges can be directed or undirected, weighted or unweighted. A grid maze is a graph: each open cell is a vertex, and each adjacent open cell is an edge. The algorithms in this lesson work on the abstract graph, not on the drawing.

The two costs that matter are V, the number of vertices, and E, the number of edges. Both BFS and DFS run in O(V + E) when the graph is stored as an adjacency list, because each vertex is discovered once and each edge is examined once.

Traversal cost

2. Representations

An adjacency list stores, for each vertex, a list of its neighbours. It uses O(V + E) memory and is the default for sparse graphs. An adjacency matrix stores a V×V table of booleans or weights; it uses O(V²) memory but answers “is there an edge?” in O(1).

  • Adjacency list — sparse graphs, traversal, most interview problems.
  • Adjacency matrix — dense graphs, repeated edge queries, Floyd–Warshall.
  • Edge list — Kruskal's algorithm and offline processing.

3. Breadth-first search

BFS uses a queue. It starts at the source, marks it visited, and enqueues its neighbours. Then it dequeues the oldest vertex and repeats. Because the queue is FIFO, the search finishes all vertices at distance d before it touches distance d + 1. In an unweighted graph, the first time BFS reaches a vertex is along a shortest path.

BFS skeleton
queue = [start]; visited[start] = true
while queue not empty:
  u = queue.dequeue()
  for v in neighbours(u):
    if not visited[v]:
      visited[v] = true
      parent[v] = u
      queue.enqueue(v)

The parent array is what lets you reconstruct the path. BFS without a parent array tells you which vertices are reachable; BFS with one tells you how to get there.

4. Depth-first search

DFS uses a stack, either explicitly or through recursion. It follows one neighbour as far as possible before backtracking. DFS is the natural tool for cycle detection, topological sorting, connected components, and maze generation. It also finds a path, but not necessarily a shortest one.

Iterative DFS skeleton
stack = [start]; visited[start] = true
while stack not empty:
  u = stack.pop()
  for v in neighbours(u):
    if not visited[v]:
      visited[v] = true
      parent[v] = u
      stack.push(v)

The recursive version is shorter: mark the node, recurse on each unvisited neighbour. The call stack is the explicit stack. If the graph is deep, recursion can overflow; an iterative stack avoids that.

Example: BFS on a small undirected graph

Vertices A, B, C, D, E. Edges A–B, A–C, B–D, C–D, D–E. Start at A. BFS visits A, then B and C, then D, then E. The path to E is A–B–D–E (or A–C–D–E), length 4 vertices.

DFS from A might visit A, B, D, C, E depending on neighbour order. It still reaches E, but the path can be longer than the BFS path.

5. Paths & components

A path is a sequence of vertices connected by edges. A connected component is a maximal set of vertices that can all reach each other. Run BFS or DFS from every unvisited vertex and count how many times the search starts; that count is the number of components.

  • Unweighted shortest path — BFS.
  • Weighted shortest path — Dijkstra (non-negative weights) or Bellman–Ford.
  • Topological order — DFS finishing times on a DAG, or Kahn's algorithm.
  • Cycle detection — DFS with a recursion stack, or union-find for undirected graphs.

6. Practice

Try it

Why does BFS find the shortest path in an unweighted graph?

Try it

Why can DFS return a longer path than BFS?

Try it

What data structure does each algorithm use?

Try it

How would you count connected components in an undirected graph?

7. Resources

Open the graph playground and run BFS and DFS on the same maze. The visited count and the path length are the whole difference in one screen. Then draw a wall and watch both algorithms fail to find a path when the graph is disconnected.

Open the graph playground →

Continue the track

Open the playground for this topic

Graph Playground →

Draw walls on a grid, then run BFS or DFS and compare the visit order, the path, and the shortest-path guarantee.

Site soundtrack