[#sec:bfs]
= breadth_first_search

Performs a breadth-first traversal of a directed or undirected graph.

*Complexity:* _O(E + V)_ +
*Defined in:* `<boost/graph/breadth_first_search.hpp>`

== Example

[source,cpp]
----
include::example$algorithms/traversal/bfs.cpp[]
----

[,text]
----
include::example$algorithms/traversal/bfs.txt[]
----

'''

=== (1) Positional version

[source,cpp]
----
template <class Graph, class Buffer, class BFSVisitor,
          class ColorMap>
void breadth_first_search(const Graph& g,
    typename graph_traits<Graph>::vertex_descriptor s,
    Buffer& Q, BFSVisitor vis, ColorMap color);
----

[cols="1,2,5"]
|===
| Direction | Parameter | Description

| IN | `const Graph& g`
| A directed or undirected graph. The graph type must be a model of
  xref:concepts/VertexListGraph.adoc[Vertex List Graph] and
  xref:concepts/IncidenceGraph.adoc[Incidence Graph].

| IN | `vertex_descriptor s`
| The source vertex where the search is started.

| UTIL | `Buffer& Q`
| The queue used to determine the order in which vertices will be
  discovered. If a FIFO queue is used, then the traversal will be
  according to the usual BFS ordering. Other types of queues can be used,
  but the traversal order will be different. For example Dijkstra's
  algorithm can be implemented using a priority queue. The type `Buffer`
  must be a model of xref:concepts/property_types/Buffer.adoc[Buffer].
  The `value_type` of the buffer must be the `vertex_descriptor` type for the graph.

| IN | `BFSVisitor vis`
| A visitor object that is invoked inside the algorithm at the
  event-points specified by the xref:visitors/BFSVisitor.adoc[BFS Visitor] concept.
  The visitor object is passed by value <<notes,[1]>>.

| UTIL/OUT | `ColorMap color`
| This is used by the algorithm to keep track of its progress through the
  graph. The type `ColorMap` must be a model of
  link:../../property_map/doc/ReadWritePropertyMap.html[Read/Write Property Map]
  and its key type must be the graph's vertex descriptor type and the value type
  of the color map must model xref:concepts/property_types/ColorValue.adoc[ColorValue].
|===

'''

=== (2) Named parameter version

[source,cpp]
----
template <class Graph, class P, class T, class R>
void breadth_first_search(const Graph& g,
    typename graph_traits<Graph>::vertex_descriptor s,
    const bgl_named_params<P, T, R>& params);
----

[cols="1,2,5"]
|===
| Direction | Parameter | Description

| IN | `const Graph& g`
| A directed or undirected graph. The graph type must be a model of
  xref:concepts/VertexListGraph.adoc[Vertex List Graph] and
  xref:concepts/IncidenceGraph.adoc[Incidence Graph].

| IN | `vertex_descriptor s`
| The source vertex where the search is started.

| IN | `visitor(BFSVisitor vis)`
| A visitor object that is invoked inside the algorithm at the
  event-points specified by the xref:visitors/BFSVisitor.adoc[BFS Visitor] concept.
  The visitor object is passed by value <<notes,[1]>>. +
  *Default:* `bfs_visitor<null_visitor>`

| UTIL/OUT | `color_map(ColorMap color)`
| This is used by the algorithm to keep track of its progress through the
  graph. The user need not initialize the color map before calling
  `breadth_first_search()` since the algorithm initializes the color of every
  vertex to white at the start of the algorithm. If you need to perform multiple
  breadth-first searches on a graph (for example, if there are some disconnected
  components) then use the
  xref:algorithms/traversal/breadth_first_visit.adoc[`breadth_first_visit()`] function and
  do your own color initialization. +
   +
  The type `ColorMap` must be a model of
  link:../../property_map/doc/ReadWritePropertyMap.html[Read/Write Property Map]
  and its key type must be the graph's vertex descriptor type and the value type
  of the color map must model xref:concepts/property_types/ColorValue.adoc[ColorValue]. +
  *Default:* an
  link:../../property_map/doc/iterator_property_map.html[iterator_property_map]
  created from a `std::vector` of `default_color_type` of size
  `num_vertices(g)` and using the `i_map` for the index map.

| IN | `vertex_index_map(VertexIndexMap i_map)`
| This maps each vertex to an integer in the range `[0, num_vertices(g))`.
  This parameter is only necessary when the default color property map is used.
  The type `VertexIndexMap` must be a model of
  link:../../property_map/doc/ReadablePropertyMap.html[Readable Property Map].
  The value type of the map must be an integer type. The vertex descriptor type
  of the graph needs to be usable as the key type of the map. +
  *Default:* `get(vertex_index, g)`.
  Note: if you use this default, make sure your graph has an internal
  `vertex_index` property. For example, `adjacency_list` with `VertexList=listS`
  does not have an internal `vertex_index` property.

| UTIL | `buffer(Buffer& Q)`
| The queue used to determine the order in which vertices will be
  discovered. If a FIFO queue is used, then the traversal will be
  according to the usual BFS ordering. Other types of queues can be used,
  but the traversal order will be different. For example Dijkstra's
  algorithm can be implemented using a priority queue. The type `Buffer`
  must be a model of xref:concepts/property_types/Buffer.adoc[Buffer].
  The `value_type` of the buffer must be the `vertex_descriptor` type for the graph. +
  *Default:* `boost::queue`
|===

== Description

The `breadth_first_search()` function performs a
https://en.wikipedia.org/wiki/Breadth-first_search[breadth-first traversal]
[xref:about/bibliography.adoc#moore59[44]] of a directed
or undirected graph. A breadth-first traversal visits vertices that are
closer to the source before visiting vertices that are further away. In
this context "distance" is defined as the number of edges in the
shortest path from the source vertex. The `breadth_first_search()`
function can be used to compute the shortest path from the source to all
reachable vertices and the resulting shortest-path distances. For more
definitions related to BFS see section
xref:about/graph_theory_review.adoc#sec:bfs-algorithm[Breadth-First Search].

BFS uses two data structures to implement the traversal: a color
marker for each vertex and a queue. White vertices are undiscovered
while gray vertices are discovered but have undiscovered adjacent
vertices. Black vertices are discovered and are adjacent to only other
black or gray vertices. The algorithm proceeds by removing a vertex
_u_ from the queue and examining each out-edge _(u,v)_. If an adjacent
vertex _v_ is not already discovered, it is colored gray and placed in
the queue. After all of the out-edges are examined, vertex _u_ is
colored black and the process is repeated. Pseudo-code for the BFS
algorithm is listed below.

[cols="1a,1a"]
|===
|
----
BFS(G, s)
  for each vertex u in V[G]
    color[u] := WHITE
    d[u] := infinity
    p[u] := u
  end for
  color[s] := GRAY
  d[s] := 0
  ENQUEUE(Q, s)
  while (Q != Ø)
    u := DEQUEUE(Q)
    for each vertex v in Adj[u]
      if (color[v] = WHITE)
        color[v] := GRAY
        d[v] := d[u] + 1
        p[v] := u
        ENQUEUE(Q, v)
      else
        if (color[v] = GRAY)
          ...
        else
          ...
    end for
    color[u] := BLACK
  end while
  return (d, p)
----
|
----
.
initialize vertex u
.
.
.
.
.
.
discover vertex s
.
examine vertex u
examine edge (u,v)
(u,v) is a tree edge
.
.
.
discover vertex v
(u,v) is a non-tree edge
.
(u,v) has a gray target
.
(u,v) has a black target
.
finish vertex u
.
.
----
|===

The `breadth_first_search()` function can be extended with
user-defined actions that will be called at certain event points. The
actions must be provided in the form of a visitor object, that is, an
object whose type meets the requirements for a
xref:visitors/BFSVisitor.adoc[BFS Visitor]. In the above pseudo-code, the event
points are the labels on the right. Also a description of each event
point is given below. By default, the `breadth_first_search()`
function does not carry out any actions, not even recording distances or
predecessors. However these can be easily added using the
xref:visitors/distance_recorder.adoc[`distance_recorder`] and
xref:visitors/predecessor_recorder.adoc[`predecessor_recorder`] event
visitors.

== Visitor Event Points

* *`vis.initialize_vertex(v, g)`* is invoked on every vertex before
  the start of the search.

* *`vis.examine_vertex(u, g)`* is invoked on each vertex as it is
  removed from the queue.

* *`vis.examine_edge(e, g)`* is invoked on every out-edge of each
  vertex immediately after the vertex is removed from the queue.

* *`vis.tree_edge(e, g)`* is invoked (in addition to
  `examine_edge()`) if the edge is a tree edge. The target vertex of
  edge `e` is discovered at this time.

* *`vis.discover_vertex(u, g)`* is invoked the first time the
  algorithm encounters vertex _u_. All vertices closer to the source
  vertex have been discovered, and vertices further from the source have
  not yet been discovered.

* *`vis.non_tree_edge(e, g)`* is invoked (in addition to
  `examine_edge()`) if the edge is not a tree edge.

* *`vis.gray_target(e, g)`* is invoked (in addition to
  `non_tree_edge()`) if the target vertex is colored gray at the
  time of examination. The color gray indicates that the vertex is
  currently in the queue.

* *`vis.black_target(e, g)`* is invoked (in addition to
  `non_tree_edge()`) if the target vertex is colored black at the
  time of examination. The color black indicates that the vertex is no
  longer in the queue.

* *`vis.finish_vertex(u, g)`* is invoked after all of the out edges
  of _u_ have been examined and all of the adjacent vertices have been
  discovered.

== Example

The example in
link:../example/bfs-example.cpp[`example/bfs-example.cpp`] demonstrates
using the BGL Breadth-first search algorithm on the graph from
xref:about/graph_theory_review.adoc#fig:bfs-example[Figure 6]. The file
link:../example/bfs-example2.cpp[`example/bfs-example2.cpp`] contains
the same example, except that the `adjacency_list` class used has
`VertexList` and `EdgeList` set to `listS`.

== Notes

[[notes]]
[1] Since the visitor parameter is passed by value, if your visitor
contains state then any changes to the state during the algorithm
will be made to a copy of the visitor object, not the visitor object
passed in. Therefore you may want the visitor to hold this state by
pointer or reference.
