Class Order in which the nodes are expanded Search algorithm Graph $O(|E|) = O(b^d)$ $O(|V|) = O(b^d)$
Animated example of a breadth-first search

Breadth-first search (BFS) is an algorithm for traversing or searching tree or graph data structures. It starts at the tree root (or some arbitrary node of a graph, sometimes referred to as a `search key'[1]) and explores the neighbor nodes first, before moving to the next level neighbors. Compare BFS with the equivalent, but more memory-efficient iterative deepening depth-first search and contrast with depth-first search.

BFS was invented in the late 1950s by E. F. Moore, who used it to find the shortest path out of a maze,[2] and discovered independently by C. Y. Lee as a wire routing algorithm (published 1961).[3][4]

## Pseudocode

Input: A graph G and a starting vertex v of G

Output: All vertices reachable from v labeled as explored.

A non-recursive implementation of BFS:

```1  BFS(G, v):
2
3      for each vertex u in G.vertices:            // "G.vertices" is a set of all vertices in the graph "G"
4          u.color = WHITE                         // Mark each node in the graph as not discovered (WHITE).
5          u.distance = INFINITY                   // Since the exploration has not started,
6                                                  // set the distance to the initial node as INFINITY
7          u.parent = NIL                          // Since the exploration has not started,
8                                                  // the parent of each vertex has not been discovered.
9
10     v.color = GRAY                              // Mark the initial vertex "v" as discovered (but not explored!)
11     v.distance = 0                              // Since it is the first vertex, its distance is 0.
12     v.parent = NIL                              // Since it is the first vertex, it has no parent.
13
14     let Q be a queue                            // Creation of a queue "Q" needed for the exploration of all nodes
15     Q.enqueue(v)                                // Enqueue the initial vertex "v".
16
17     while Q is not empty:                       // Keep searching until the queue is empty
18
19         u = Q.dequeue()                         // Dequeue a vertex "u" to visit its children.
20
23                 adj.color = GRAY                // mark it as discovered
24                 adj.distance = u.distance + 1   // The distance of "adj" from the initial node "v"
25                                                 // is equal to the distance of "u"
26                                                 // from the initial node "v" + 1.
27                 adj.parent = u                  // Since we have discovered "adj" from "u"
28                                                 // "u" becomes the parent of "adj".
30
31         u.color = BLACK                         // Since we have finished visiting the children of "u"
32                                                 // we can mark "u" as explored.
```

This non-recursive implementation is similar to the non-recursive implementation of depth-first search, but differs from it in two ways:

1. it uses a queue instead of a stack and
2. it checks whether a vertex has been discovered before enqueueing the vertex rather than delaying this check until the vertex is dequeued from the queue.

We use three colours to represent the states of a vertex:

1. WHITE means not discovered
2. GRAY means discovered (or visited) but not explored (children nodes have not been visited)
3. BLACK means explored (all the children nodes have been visited)

The distance attribute of each vertex (or node) is needed for example when searching for the shortest path between nodes in a graph. At the beginning of the algorithm, the distance of each vertex is set to INFINITY, which is just a word that represents the fact that a node has not been reached yet, and therefore it has no distance from the starting vertex. We could have used other symbols, such as -1, to represent this concept.

The parent attribute of each vertex can also be useful to access the nodes in a shortest path, for example by backtracking from the destination node up to the starting node, once the BFS has been run, and the predecessors nodes have been set.

The NIL is just a symbol that represents the absence of something, in this case it represents the absence of a parent (or predecessor) node; sometimes instead of the word NIL, words such as null, none or nothing can also be used.

Note that the word node is usually interchangeable with the word vertex.

Breadth-first search produces a so-called breadth first tree. You can see how a breadth first tree looks in the following example.

### Example

The following is an example where BFS is applied on map of Germany. You can also see the breadth-first tree obtained when running BFS on the same map, starting from Frankfurt:

An example map of Germany with some connections between cities
The breadth-first tree obtained when running BFS on the given map and starting in Frankfurt

## Analysis

### Time and space complexity

The time complexity can be expressed as $O(|V|+|E|)$,[5] since every vertex and every edge will be explored in the worst case. $|V|$ is the number of vertices and $|E|$ is the number of edges in the graph. Note that $O(|E|)$ may vary between $O(1)$ and $O(|V|^2)$, depending on how sparse the input graph is.

When the number of vertices in the graph is known ahead of time, and additional data structures are used to determine which vertices have already been added to the queue, the space complexity can be expressed as $O(|V|)$, where $|V|$ is the cardinality of the set of vertices (as said before). If the graph is represented by an adjacency list it occupies $\Theta(|V|+|E|)$[6] space in memory, while an adjacency matrix representation occupies $\Theta(|V|^2)$.[7]

When working with graphs that are too large to store explicitly (or infinite), it is more practical to describe the complexity of breadth-first search in different terms: to find the nodes that are at distance d from the start node (measured in number of edge traversals), BFS takes O(bd + 1) time and memory, where b is the "branching factor" of the graph (the average out-degree).[8]:81

### Completeness and optimality

In the analysis of algorithms, the input to breadth-first search is assumed to be a finite graph, represented explicitly as an adjacency list or similar representation. However, in the application of graph traversal methods in artificial intelligence the input may be an implicit representation of an infinite graph. In this context, a search method is described as being complete if it is guaranteed to find a goal state if one exists. Breadth-first search is complete, but depth-first search is not: when applied to infinite graphs represented implicitly, it may get lost in parts of the graph that have no goal state and never return.[9]

## Applications

Breadth-first search can be used to solve many problems in graph theory, for example:

### Testing bipartiteness

BFS can be used to test bipartiteness, by starting the search at any vertex and giving alternating labels to the vertices visited during the search. That is, give label 0 to the starting vertex, 1 to all its neighbors, 0 to those neighbors' neighbors, and so on. If at any step a vertex has (visited) neighbors with the same label as itself, then the graph is not bipartite. If the search ends without such a situation occurring, then the graph is bipartite.