Reading preferences
Concept

Breadth-First and Depth-First Search

Explore a graph layer by layer or follow one path before returning.

breadth first search, depth first search, bfs, dfs, graphs

Explore a neighbourhood

Imagine starting at your home on a map. You could visit every directly connected street first, then streets two connections away. Or you could follow one street as far as possible, return to a junction, and try another.

These are two ways to search a graph. Breadth-first search (BFS) explores in layers. Depth-first search (DFS) explores a path before coming back to another choice.

Why use them and where they help

BFS helps find a route with the fewest edges in an unweighted graph. DFS can explore reachable places and support tasks such as checking connections. Both also work on directed graphs when neighbour lists contain outgoing edges. Neither method by itself finds the cheapest route when edges have different costs.

Follow both searches

Start at A and take neighbours in the listed order:

       A
      / \
     B   C
      \ /
       D     E

The undirected edges are A–B, A–C, B–D, C–D. E is isolated.

MethodVisit order from AIdea
BFSA, B, C, DFinish each layer before the next
DFSA, B, D, CFollow B to D before returning

These orders depend on the order of neighbours; other correct orders are possible. Neither search reaches isolated E from A. To cover the whole graph, start again from each still-unvisited vertex.

See the reasoning

Follow the example one step at a time

Follow breadth-first search from A, visiting neighbours in the lesson's order. This is a prepared teaching demonstration, not live code execution.

Start

A—B
| |
C—D    E isolated
queue: [A]   visited: A

Mark A when it is added to the queue. E has no connection to A.

Python illustration

from collections import deque

graph = {
    "A": ["B", "C"],
    "B": ["A", "D"],
    "C": ["A", "D"],
    "D": ["B", "C"],
    "E": [],
}


def breadth_first(graph, start):
    seen = {start}
    waiting = deque([start])
    order = []
    while waiting:
        vertex = waiting.popleft()
        order.append(vertex)
        for neighbour in graph[vertex]:
            if neighbour not in seen:
                seen.add(neighbour)
                waiting.append(neighbour)
    return order


def depth_first(graph, start):
    seen = set()
    order = []

    def visit(vertex):
        seen.add(vertex)
        order.append(vertex)
        for neighbour in graph[vertex]:
            if neighbour not in seen:
                visit(neighbour)

    visit(start)
    return order


print(breadth_first(graph, "A"))
print(depth_first(graph, "A"))
print(breadth_first(graph, "E"))

Prepared output — not live execution:

['A', 'B', 'C', 'D']
['A', 'B', 'D', 'C']
['E']

Both functions require a start key and a key for every listed neighbour; missing keys raise KeyError. BFS marks a vertex when it enters the queue, so two neighbours do not enqueue it twice. The recursive DFS uses the call stack. These functions return visitation orders, not paths; to reconstruct a BFS shortest path, save the parent that first discovered each vertex.

Time, space, and common mistakes

With adjacency lists, both methods take O(V + E) time over reachable vertices and their edges, assuming expected O(1) set operations. They use O(V) extra space for seen vertices and the queue or recursion stack, plus returned output. Recursive DFS can hit Python's recursion limit on a deep graph. Remembering visited nodes is essential in a graph with cycles.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. What order does breadth-first search explore?
2. What does depth-first search do before returning to another choice?
3. Why remember visited vertices?
4. When does BFS find the fewest-edge route from the start?

References and further reading