Skip to content
IT glossary
AlgorithmsUpdated December 3, 2026

Breadth-first search

Поиск в ширину

This graph search visits the starting point, then everything one step away, then everything two steps away, and so on. It finds routes that use the fewest edges.

Also known as: BFS

Think in layers

Breadth-first search (BFS) explores a graph outward from a starting vertex. The start is layer zero, its immediate neighbors are layer one, and any new vertices reached from those neighbors are layer two. In a family tree, the same idea lets you list descendants one generation at a time. In a maze, it lets you find an exit using the fewest moves, as long as each legal move counts the same.

What the queue guarantees

BFS uses a first-in, first-out (FIFO) queue. Put the start in the queue and mark it as discovered. Take a vertex off the front, inspect its neighbors, and add each undiscovered neighbor to the back, marking it as you go. For a directed graph, follow only outgoing edges.

When you process a vertex at distance d, a newly discovered neighbor goes to the back of the queue with distance d + 1. Vertices still waiting at distance d are processed before anything in that next layer. That is why the first route you find to a vertex uses the fewest edges: a shorter route would have reached it from an earlier layer. The order of neighbors can change which route you find when several are equally short, but not the distance.

Example: Find the minimum number of hops

from collections import deque

def min_hops(graph, start, goal):
    queue = deque([start])
    distance = {start: 0}
    while queue:
        node = queue.popleft()
        if node == goal:
            return distance[node]
        for neighbor in graph.get(node, ()):
            if neighbor not in distance:
                distance[neighbor] = distance[node] + 1
                queue.append(neighbor)
    return None

With edges A → B, A → C, and B → C, the result from A to C is 1, even if B appears first in A's neighbor list. The function returns 0 if the goal is the start and None if the goal is unreachable. To return the route instead of just its length, record each vertex's predecessor when you first enqueue it, then follow those pointers backward from the goal and reverse the list.

Cost and common mistakes

With adjacency lists, BFS takes O(V + E) time in the worst case and uses O(V) extra space, where V is the number of vertices and E is the number of edges. It scans the adjacency list of each reachable vertex at most once. Marking vertices only when they leave the queue can let several neighbors enqueue the same vertex, wasting time and space. In Python, use deque.popleft() instead of list.pop(0), which shifts all remaining elements.

A stack gives you depth-first search (DFS), which can find a route but does not guarantee the fewest hops. Standard BFS counts edges, not travel time or monetary cost. If edges have different nonnegative weights and you need the lowest total cost, use Dijkstra's algorithm.

In interviews

Look for problems that ask for the fewest moves, swaps, or transformations. Treat each state as a vertex and each allowed action as an edge. You often don't need to build the graph in advance: for a grid, generate each cell's legal neighbors as you visit it. Explain what your visited key represents, especially if two states at the same location have different options, such as when one has a key and the other doesn't.