/* -*- mode: C++; indent-tabs-mode: nil; -*-
* This file is a part of LEMON, a generic C++ optimization library.
* Copyright (C) 2003-2009
* Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
* (Egervary Research Group on Combinatorial Optimization, EGRES).
* Permission to use, modify and distribute this software is granted
* provided that this copyright notice appears in all copies. For
* precise terms see the accompanying LICENSE file.
* This software is provided "AS IS" with no warranty of any kind,
* express or implied, and with no claim as to its suitability for any
#include <lemon/list_graph.h>
#include <lemon/bits/path_dump.h>
///Default traits class of Bfs class.
///Default traits class of Bfs class.
///\tparam GR Digraph type.
///The type of the digraph the algorithm runs on.
///\brief The type of the map that stores the predecessor
///arcs of the shortest paths.
///The type of the map that stores the predecessor
///arcs of the shortest paths.
///It must meet the \ref concepts::WriteMap "WriteMap" concept.
typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
///Instantiates a PredMap.
///This function instantiates a PredMap.
///\param g is the digraph, to which we would like to define the
static PredMap *createPredMap(const Digraph &g)
///The type of the map that indicates which nodes are processed.
///The type of the map that indicates which nodes are processed.
///It must meet the \ref concepts::WriteMap "WriteMap" concept.
typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
///Instantiates a ProcessedMap.
///This function instantiates a ProcessedMap.
///\param g is the digraph, to which
///we would like to define the ProcessedMap
static ProcessedMap *createProcessedMap(const Digraph &g)
static ProcessedMap *createProcessedMap(const Digraph &)
return new ProcessedMap();
///The type of the map that indicates which nodes are reached.
///The type of the map that indicates which nodes are reached.
///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
typedef typename Digraph::template NodeMap<bool> ReachedMap;
///Instantiates a ReachedMap.
///This function instantiates a ReachedMap.
///\param g is the digraph, to which
///we would like to define the ReachedMap.
static ReachedMap *createReachedMap(const Digraph &g)
return new ReachedMap(g);
///The type of the map that stores the distances of the nodes.
///The type of the map that stores the distances of the nodes.
///It must meet the \ref concepts::WriteMap "WriteMap" concept.
typedef typename Digraph::template NodeMap<int> DistMap;
///Instantiates a DistMap.
///This function instantiates a DistMap.
///\param g is the digraph, to which we would like to define the
static DistMap *createDistMap(const Digraph &g)
///This class provides an efficient implementation of the %BFS algorithm.
///There is also a \ref bfs() "function-type interface" for the BFS
///algorithm, which is convenient in the simplier cases and it can be
///\tparam GR The type of the digraph the algorithm runs on.
///The default type is \ref ListDigraph.
template <typename GR=ListDigraph,
typename TR=BfsDefaultTraits<GR> >
///The type of the digraph the algorithm runs on.
typedef typename TR::Digraph Digraph;
///\brief The type of the map that stores the predecessor arcs of the
typedef typename TR::PredMap PredMap;
///The type of the map that stores the distances of the nodes.
typedef typename TR::DistMap DistMap;
///The type of the map that indicates which nodes are reached.
typedef typename TR::ReachedMap ReachedMap;
///The type of the map that indicates which nodes are processed.
typedef typename TR::ProcessedMap ProcessedMap;
///The type of the paths.
typedef PredMapPath<Digraph, PredMap> Path;
///The \ref BfsDefaultTraits "traits class" of the algorithm.
typedef typename Digraph::Node Node;
typedef typename Digraph::NodeIt NodeIt;
typedef typename Digraph::Arc Arc;
typedef typename Digraph::OutArcIt OutArcIt;
//Pointer to the underlying digraph.
//Pointer to the map of predecessor arcs.
//Indicates if _pred is locally allocated (true) or not.
//Pointer to the map of distances.
//Indicates if _dist is locally allocated (true) or not.
//Pointer to the map of reached status of the nodes.
//Indicates if _reached is locally allocated (true) or not.
//Pointer to the map of processed status of the nodes.
ProcessedMap *_processed;
//Indicates if _processed is locally allocated (true) or not.
std::vector<typename Digraph::Node> _queue;
int _queue_head,_queue_tail,_queue_next_dist;
//Creates the maps if necessary.
_pred = Traits::createPredMap(*G);
_dist = Traits::createDistMap(*G);
_reached = Traits::createReachedMap(*G);
_processed = Traits::createProcessedMap(*G);
///\name Named Template Parameters
struct SetPredMapTraits : public Traits {
static PredMap *createPredMap(const Digraph &)
LEMON_ASSERT(false, "PredMap is not initialized");
return 0; // ignore warnings
///\brief \ref named-templ-param "Named parameter" for setting
///\ref named-templ-param "Named parameter" for setting
///It must meet the \ref concepts::WriteMap "WriteMap" concept.
struct SetPredMap : public Bfs< Digraph, SetPredMapTraits<T> > {
typedef Bfs< Digraph, SetPredMapTraits<T> > Create;
struct SetDistMapTraits : public Traits {
static DistMap *createDistMap(const Digraph &)
LEMON_ASSERT(false, "DistMap is not initialized");
return 0; // ignore warnings
///\brief \ref named-templ-param "Named parameter" for setting
///\ref named-templ-param "Named parameter" for setting
///It must meet the \ref concepts::WriteMap "WriteMap" concept.
struct SetDistMap : public Bfs< Digraph, SetDistMapTraits<T> > {
typedef Bfs< Digraph, SetDistMapTraits<T> > Create;
struct SetReachedMapTraits : public Traits {
static ReachedMap *createReachedMap(const Digraph &)
LEMON_ASSERT(false, "ReachedMap is not initialized");
return 0; // ignore warnings
///\brief \ref named-templ-param "Named parameter" for setting
///\ref named-templ-param "Named parameter" for setting
///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
struct SetReachedMap : public Bfs< Digraph, SetReachedMapTraits<T> > {
typedef Bfs< Digraph, SetReachedMapTraits<T> > Create;
struct SetProcessedMapTraits : public Traits {
static ProcessedMap *createProcessedMap(const Digraph &)
LEMON_ASSERT(false, "ProcessedMap is not initialized");
return 0; // ignore warnings
///\brief \ref named-templ-param "Named parameter" for setting
///\ref named-templ-param "Named parameter" for setting
///It must meet the \ref concepts::WriteMap "WriteMap" concept.
struct SetProcessedMap : public Bfs< Digraph, SetProcessedMapTraits<T> > {
typedef Bfs< Digraph, SetProcessedMapTraits<T> > Create;
struct SetStandardProcessedMapTraits : public Traits {
typedef typename Digraph::template NodeMap<bool> ProcessedMap;
static ProcessedMap *createProcessedMap(const Digraph &g)
return new ProcessedMap(g);
return 0; // ignore warnings
///\brief \ref named-templ-param "Named parameter" for setting
///ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
///\ref named-templ-param "Named parameter" for setting
///ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
///If you don't set it explicitly, it will be automatically allocated.
struct SetStandardProcessedMap :
public Bfs< Digraph, SetStandardProcessedMapTraits > {
typedef Bfs< Digraph, SetStandardProcessedMapTraits > Create;
///\param g The digraph the algorithm runs on.
_pred(NULL), local_pred(false),
_dist(NULL), local_dist(false),
_reached(NULL), local_reached(false),
_processed(NULL), local_processed(false)
if(local_pred) delete _pred;
if(local_dist) delete _dist;
if(local_reached) delete _reached;
if(local_processed) delete _processed;
///Sets the map that stores the predecessor arcs.
///Sets the map that stores the predecessor arcs.
///If you don't use this function before calling \ref run(Node) "run()"
///or \ref init(), an instance will be allocated automatically.
///The destructor deallocates this automatically allocated map,
///\return <tt> (*this) </tt>
///Sets the map that indicates which nodes are reached.
///Sets the map that indicates which nodes are reached.
///If you don't use this function before calling \ref run(Node) "run()"
///or \ref init(), an instance will be allocated automatically.
///The destructor deallocates this automatically allocated map,
///\return <tt> (*this) </tt>
Bfs &reachedMap(ReachedMap &m)
///Sets the map that indicates which nodes are processed.
///Sets the map that indicates which nodes are processed.
///If you don't use this function before calling \ref run(Node) "run()"
///or \ref init(), an instance will be allocated automatically.
///The destructor deallocates this automatically allocated map,
///\return <tt> (*this) </tt>
Bfs &processedMap(ProcessedMap &m)
///Sets the map that stores the distances of the nodes.
///Sets the map that stores the distances of the nodes calculated by
///If you don't use this function before calling \ref run(Node) "run()"
///or \ref init(), an instance will be allocated automatically.
///The destructor deallocates this automatically allocated map,
///\return <tt> (*this) </tt>
///\name Execution Control
///The simplest way to execute the BFS algorithm is to use one of the
///member functions called \ref run(Node) "run()".\n
///If you need more control on the execution, first you have to call
///\ref init(), then you can add several source nodes with
///\ref addSource(). Finally the actual path computation can be
///performed with one of the \ref start() functions.
///\brief Initializes the internal data structures.
///Initializes the internal data structures.
_queue.resize(countNodes(*G));
_queue_head=_queue_tail=0;
for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
_processed->set(u,false);
///Adds a new source node.
///Adds a new source node to the set of nodes to be processed.
_queue_next_dist=_queue_head;
///Processes the next node.
///Processes the next node.
///\return The processed node.
///\pre The queue must not be empty.
if(_queue_tail==_queue_next_dist) {
_queue_next_dist=_queue_head;
Node n=_queue[_queue_tail++];
for(OutArcIt e(*G,n);e!=INVALID;++e)
if(!(*_reached)[m=G->target(e)]) {
_dist->set(m,_curr_dist);
///Processes the next node.
///Processes the next node and checks if the given target node
///is reached. If the target node is reachable from the processed
///node, then the \c reach parameter will be set to \c true.
///\param target The target node.
///\retval reach Indicates if the target node is reached.
///It should be initially \c false.
///\return The processed node.
///\pre The queue must not be empty.
Node processNextNode(Node target, bool& reach)
if(_queue_tail==_queue_next_dist) {
_queue_next_dist=_queue_head;
Node n=_queue[_queue_tail++];
for(OutArcIt e(*G,n);e!=INVALID;++e)
if(!(*_reached)[m=G->target(e)]) {
_dist->set(m,_curr_dist);
reach = reach || (target == m);
///Processes the next node.
///Processes the next node and checks if at least one of reached
///nodes has \c true value in the \c nm node map. If one node
///with \c true value is reachable from the processed node, then the
///\c rnode parameter will be set to the first of such nodes.
///\param nm A \c bool (or convertible) node map that indicates the
///\retval rnode The reached target node.
///It should be initially \c INVALID.
///\return The processed node.
///\pre The queue must not be empty.
Node processNextNode(const NM& nm, Node& rnode)
if(_queue_tail==_queue_next_dist) {
_queue_next_dist=_queue_head;
Node n=_queue[_queue_tail++];
for(OutArcIt e(*G,n);e!=INVALID;++e)
if(!(*_reached)[m=G->target(e)]) {
_dist->set(m,_curr_dist);
if (nm[m] && rnode == INVALID) rnode = m;
///The next node to be processed.
///Returns the next node to be processed or \c INVALID if the queue
return _queue_tail<_queue_head?_queue[_queue_tail]:INVALID;
///Returns \c false if there are nodes to be processed.
///Returns \c false if there are nodes to be processed
bool emptyQueue() const { return _queue_tail==_queue_head; }
///Returns the number of the nodes to be processed.
///Returns the number of the nodes to be processed
int queueSize() const { return _queue_head-_queue_tail; }
///Executes the algorithm.
///Executes the algorithm.
///This method runs the %BFS algorithm from the root node(s)
///in order to compute the shortest path to each node.
///The algorithm computes
///- the shortest path tree (forest),
///- the distance of each node from the root(s).
///\pre init() must be called and at least one root node should be
///added with addSource() before using this function.
///\note <tt>b.start()</tt> is just a shortcut of the following code.
/// while ( !b.emptyQueue() ) {
while ( !emptyQueue() ) processNextNode();
///Executes the algorithm until the given target node is reached.
///Executes the algorithm until the given target node is reached.
///This method runs the %BFS algorithm from the root node(s)
///in order to compute the shortest path to \c t.
///The algorithm computes
///- the shortest path to \c t,
///- the distance of \c t from the root(s).
///\pre init() must be called and at least one root node should be
///added with addSource() before using this function.
///\note <tt>b.start(t)</tt> is just a shortcut of the following code.
/// while ( !b.emptyQueue() && !reach ) {
/// b.processNextNode(t, reach);
while ( !emptyQueue() && !reach ) processNextNode(t, reach);
///Executes the algorithm until a condition is met.
///Executes the algorithm until a condition is met.
///This method runs the %BFS algorithm from the root node(s) in
///order to compute the shortest path to a node \c v with
/// <tt>nm[v]</tt> true, if such a node can be found.
///\param nm A \c bool (or convertible) node map. The algorithm
///will stop when it reaches a node \c v with <tt>nm[v]</tt> true.
///\return The reached node \c v with <tt>nm[v]</tt> true or
///\c INVALID if no such node was found.
///\pre init() must be called and at least one root node should be
///added with addSource() before using this function.
///\note <tt>b.start(nm)</tt> is just a shortcut of the following code.
/// Node rnode = INVALID;
/// while ( !b.emptyQueue() && rnode == INVALID ) {
/// b.processNextNode(nm, rnode);
template<class NodeBoolMap>
Node start(const NodeBoolMap &nm)
while ( !emptyQueue() && rnode == INVALID ) {
processNextNode(nm, rnode);
///Runs the algorithm from the given source node.
///This method runs the %BFS algorithm from node \c s
///in order to compute the shortest path to each node.
///The algorithm computes
///- the shortest path tree,
///- the distance of each node from the root.
///\note <tt>b.run(s)</tt> is just a shortcut of the following code.
///Finds the shortest path between \c s and \c t.
///This method runs the %BFS algorithm from node \c s
///in order to compute the shortest path to node \c t
///(it stops searching when \c t is processed).
///\return \c true if \c t is reachable form \c s.
///\note Apart from the return value, <tt>b.run(s,t)</tt> is just a
///shortcut of the following code.
bool run(Node s,Node t) {
///Runs the algorithm to visit all nodes in the digraph.
///This method runs the %BFS algorithm in order to
///compute the shortest path to each node.
///The algorithm computes
///- the shortest path tree (forest),
///- the distance of each node from the root(s).
///\note <tt>b.run(s)</tt> is just a shortcut of the following code.
/// for (NodeIt n(gr); n != INVALID; ++n) {
for (NodeIt n(*G); n != INVALID; ++n) {
///The results of the BFS algorithm can be obtained using these
///Either \ref run(Node) "run()" or \ref start() should be called
///The shortest path to a node.
///Returns the shortest path to a node.
///\warning \c t should be reached from the root(s).
///\pre Either \ref run(Node) "run()" or \ref init()
///must be called before using this function.
Path path(Node t) const { return Path(*G, *_pred, t); }
///The distance of a node from the root(s).
///Returns the distance of a node from the root(s).
///\warning If node \c v is not reached from the root(s), then
///the return value of this function is undefined.
///\pre Either \ref run(Node) "run()" or \ref init()
///must be called before using this function.
int dist(Node v) const { return (*_dist)[v]; }
///Returns the 'previous arc' of the shortest path tree for a node.
///This function returns the 'previous arc' of the shortest path
///tree for the node \c v, i.e. it returns the last arc of a
///shortest path from a root to \c v. It is \c INVALID if \c v
///is not reached from the root(s) or if \c v is a root.
///The shortest path tree used here is equal to the shortest path
///tree used in \ref predNode().
///\pre Either \ref run(Node) "run()" or \ref init()
///must be called before using this function.
Arc predArc(Node v) const { return (*_pred)[v];}
///Returns the 'previous node' of the shortest path tree for a node.
///This function returns the 'previous node' of the shortest path
///tree for the node \c v, i.e. it returns the last but one node
///from a shortest path from a root to \c v. It is \c INVALID
///if \c v is not reached from the root(s) or if \c v is a root.
///The shortest path tree used here is equal to the shortest path
///tree used in \ref predArc().
///\pre Either \ref run(Node) "run()" or \ref init()
///must be called before using this function.
Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
G->source((*_pred)[v]); }
///\brief Returns a const reference to the node map that stores the
/// distances of the nodes.
///Returns a const reference to the node map that stores the distances
///of the nodes calculated by the algorithm.
///\pre Either \ref run(Node) "run()" or \ref init()
///must be called before using this function.
const DistMap &distMap() const { return *_dist;}
///\brief Returns a const reference to the node map that stores the
///Returns a const reference to the node map that stores the predecessor
///arcs, which form the shortest path tree.
///\pre Either \ref run(Node) "run()" or \ref init()
///must be called before using this function.
const PredMap &predMap() const { return *_pred;}
///Checks if a node is reached from the root(s).
///Returns \c true if \c v is reached from the root(s).
///\pre Either \ref run(Node) "run()" or \ref init()
///must be called before using this function.
bool reached(Node v) const { return (*_reached)[v]; }
///Default traits class of bfs() function.
///Default traits class of bfs() function.
///\tparam GR Digraph type.
struct BfsWizardDefaultTraits
///The type of the digraph the algorithm runs on.
///\brief The type of the map that stores the predecessor
///arcs of the shortest paths.
///The type of the map that stores the predecessor
///arcs of the shortest paths.
///It must meet the \ref concepts::WriteMap "WriteMap" concept.
typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
///Instantiates a PredMap.
///This function instantiates a PredMap.
///\param g is the digraph, to which we would like to define the
static PredMap *createPredMap(const Digraph &g)
///The type of the map that indicates which nodes are processed.
///The type of the map that indicates which nodes are processed.
///It must meet the \ref concepts::WriteMap "WriteMap" concept.
///By default it is a NullMap.
typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
///Instantiates a ProcessedMap.
///This function instantiates a ProcessedMap.
///\param g is the digraph, to which
///we would like to define the ProcessedMap.
static ProcessedMap *createProcessedMap(const Digraph &g)
static ProcessedMap *createProcessedMap(const Digraph &)
return new ProcessedMap();
///The type of the map that indicates which nodes are reached.
///The type of the map that indicates which nodes are reached.
///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
typedef typename Digraph::template NodeMap<bool> ReachedMap;
///Instantiates a ReachedMap.
///This function instantiates a ReachedMap.
///\param g is the digraph, to which
///we would like to define the ReachedMap.
static ReachedMap *createReachedMap(const Digraph &g)
return new ReachedMap(g);
///The type of the map that stores the distances of the nodes.
///The type of the map that stores the distances of the nodes.
///It must meet the \ref concepts::WriteMap "WriteMap" concept.
typedef typename Digraph::template NodeMap<int> DistMap;
///Instantiates a DistMap.
///This function instantiates a DistMap.
///\param g is the digraph, to which we would like to define
static DistMap *createDistMap(const Digraph &g)
///The type of the shortest paths.
///The type of the shortest paths.
///It must meet the \ref concepts::Path "Path" concept.
typedef lemon::Path<Digraph> Path;
/// Default traits class used by BfsWizard
/// To make it easier to use Bfs algorithm
/// we have created a wizard class.
/// This \ref BfsWizard class needs default traits,
/// as well as the \ref Bfs class.
/// The \ref BfsWizardBase is a class to be the default traits of the
/// \ref BfsWizard class.
class BfsWizardBase : public BfsWizardDefaultTraits<GR>
typedef BfsWizardDefaultTraits<GR> Base;
//The type of the nodes in the digraph.
typedef typename Base::Digraph::Node Node;
//Pointer to the digraph the algorithm runs on.
//Pointer to the map of reached nodes.
//Pointer to the map of processed nodes.
//Pointer to the map of predecessors arcs.
//Pointer to the map of distances.
//Pointer to the shortest path to the target node.
//Pointer to the distance of the target node.
/// This constructor does not require parameters, therefore it initiates
/// all of the attributes to \c 0.
BfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0),
_dist(0), _path(0), _di(0) {}
/// This constructor requires one parameter,
/// others are initiated to \c 0.
/// \param g The digraph the algorithm runs on.
BfsWizardBase(const GR &g) :
_g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
_reached(0), _processed(0), _pred(0), _dist(0), _path(0), _di(0) {}
/// Auxiliary class for the function-type interface of BFS algorithm.
/// This auxiliary class is created to implement the
/// \ref bfs() "function-type interface" of \ref Bfs algorithm.
/// It does not have own \ref run(Node) "run()" method, it uses the
/// functions and features of the plain \ref Bfs.
/// This class should only be used through the \ref bfs() function,
/// which makes it easier to use the algorithm.
class BfsWizard : public TR
///The type of the digraph the algorithm runs on.
typedef typename TR::Digraph Digraph;
typedef typename Digraph::Node Node;
typedef typename Digraph::NodeIt NodeIt;
typedef typename Digraph::Arc Arc;
typedef typename Digraph::OutArcIt OutArcIt;
///\brief The type of the map that stores the predecessor
///arcs of the shortest paths.
typedef typename TR::PredMap PredMap;
///\brief The type of the map that stores the distances of the nodes.
typedef typename TR::DistMap DistMap;
///\brief The type of the map that indicates which nodes are reached.
typedef typename TR::ReachedMap ReachedMap;
///\brief The type of the map that indicates which nodes are processed.
typedef typename TR::ProcessedMap ProcessedMap;
///The type of the shortest paths
typedef typename TR::Path Path;
/// Constructor that requires parameters.
/// Constructor that requires parameters.
/// These parameters will be the default values for the traits class.
/// \param g The digraph the algorithm runs on.
BfsWizard(const Digraph &g) :
BfsWizard(const TR &b) : TR(b) {}
///Runs BFS algorithm from the given source node.
///This method runs BFS algorithm from node \c s
///in order to compute the shortest path to each node.
Bfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
///Finds the shortest path between \c s and \c t.
///This method runs BFS algorithm from node \c s
///in order to compute the shortest path to node \c t
///(it stops searching when \c t is processed).
///\return \c true if \c t is reachable form \c s.
Bfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
*reinterpret_cast<Path*>(Base::_path) = alg.path(t);
*Base::_di = alg.dist(t);
///Runs BFS algorithm to visit all nodes in the digraph.
///This method runs BFS algorithm in order to compute
///the shortest path to each node.
struct SetPredMapBase : public Base {
static PredMap *createPredMap(const Digraph &) { return 0; };
SetPredMapBase(const TR &b) : TR(b) {}
///\brief \ref named-func-param "Named parameter"
///for setting PredMap object.
///\ref named-func-param "Named parameter"
///for setting PredMap object.
BfsWizard<SetPredMapBase<T> > predMap(const T &t)
Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
return BfsWizard<SetPredMapBase<T> >(*this);
struct SetReachedMapBase : public Base {
static ReachedMap *createReachedMap(const Digraph &) { return 0; };
SetReachedMapBase(const TR &b) : TR(b) {}
///\brief \ref named-func-param "Named parameter"
///for setting ReachedMap object.
/// \ref named-func-param "Named parameter"
///for setting ReachedMap object.
BfsWizard<SetReachedMapBase<T> > reachedMap(const T &t)
Base::_reached=reinterpret_cast<void*>(const_cast<T*>(&t));
return BfsWizard<SetReachedMapBase<T> >(*this);
struct SetDistMapBase : public Base {
static DistMap *createDistMap(const Digraph &) { return 0; };
SetDistMapBase(const TR &b) : TR(b) {}
///\brief \ref named-func-param "Named parameter"
///for setting DistMap object.
/// \ref named-func-param "Named parameter"
///for setting DistMap object.
BfsWizard<SetDistMapBase<T> > distMap(const T &t)
Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
return BfsWizard<SetDistMapBase<T> >(*this);
struct SetProcessedMapBase : public Base {
static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
SetProcessedMapBase(const TR &b) : TR(b) {}
///\brief \ref named-func-param "Named parameter"
///for setting ProcessedMap object.
/// \ref named-func-param "Named parameter"
///for setting ProcessedMap object.
BfsWizard<SetProcessedMapBase<T> > processedMap(const T &t)
Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
return BfsWizard<SetProcessedMapBase<T> >(*this);
struct SetPathBase : public Base {
SetPathBase(const TR &b) : TR(b) {}
///\brief \ref named-func-param "Named parameter"
///for getting the shortest path to the target node.
///\ref named-func-param "Named parameter"
///for getting the shortest path to the target node.
BfsWizard<SetPathBase<T> > path(const T &t)
Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t));
return BfsWizard<SetPathBase<T> >(*this);
///\brief \ref named-func-param "Named parameter"
///for getting the distance of the target node.
///\ref named-func-param "Named parameter"
///for getting the distance of the target node.
BfsWizard dist(const int &d)
Base::_di=const_cast<int*>(&d);
///Function-type interface for BFS algorithm.
///Function-type interface for BFS algorithm.
///This function also has several \ref named-func-param "named parameters",
///they are declared as the members of class \ref BfsWizard.
///The following examples show how to use these parameters.
/// // Compute shortest path from node s to each node
/// bfs(g).predMap(preds).distMap(dists).run(s);
/// // Compute shortest path from s to t
/// bool reached = bfs(g).path(p).dist(d).run(s,t);
///\warning Don't forget to put the \ref BfsWizard::run(Node) "run()"
///to the end of the parameter list.
BfsWizard<BfsWizardBase<GR> >
return BfsWizard<BfsWizardBase<GR> >(digraph);
/// \brief Visitor class for BFS.
/// This class defines the interface of the BfsVisit events, and
/// it could be the base of a real visitor class.
template <typename _Digraph>
typedef _Digraph Digraph;
typedef typename Digraph::Arc Arc;
typedef typename Digraph::Node Node;
/// \brief Called for the source node(s) of the BFS.
/// This function is called for the source node(s) of the BFS.
void start(const Node& node) {}
/// \brief Called when a node is reached first time.
/// This function is called when a node is reached first time.
void reach(const Node& node) {}
/// \brief Called when a node is processed.
/// This function is called when a node is processed.
void process(const Node& node) {}
/// \brief Called when an arc reaches a new node.
/// This function is called when the BFS finds an arc whose target node
void discover(const Arc& arc) {}
/// \brief Called when an arc is examined but its target node is
/// This function is called when an arc is examined but its target node is
void examine(const Arc& arc) {}
template <typename _Digraph>
typedef _Digraph Digraph;
typedef typename Digraph::Arc Arc;
typedef typename Digraph::Node Node;
void start(const Node&) {}
void reach(const Node&) {}
void process(const Node&) {}
void discover(const Arc&) {}
void examine(const Arc&) {}
template <typename _Visitor>
/// \brief Default traits class of BfsVisit class.
/// Default traits class of BfsVisit class.
/// \tparam _Digraph The type of the digraph the algorithm runs on.
struct BfsVisitDefaultTraits {
/// \brief The type of the digraph the algorithm runs on.
typedef _Digraph Digraph;
/// \brief The type of the map that indicates which nodes are reached.
/// The type of the map that indicates which nodes are reached.
/// It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
typedef typename Digraph::template NodeMap<bool> ReachedMap;
/// \brief Instantiates a ReachedMap.
/// This function instantiates a ReachedMap.
/// \param digraph is the digraph, to which
/// we would like to define the ReachedMap.
static ReachedMap *createReachedMap(const Digraph &digraph) {
return new ReachedMap(digraph);
/// \brief %BFS algorithm class with visitor interface.
/// This class provides an efficient implementation of the %BFS algorithm
/// with visitor interface.
/// The %BfsVisit class provides an alternative interface to the Bfs
/// class. It works with callback mechanism, the BfsVisit object calls
/// the member functions of the \c Visitor class on every BFS event.
/// This interface of the BFS algorithm should be used in special cases
/// when extra actions have to be performed in connection with certain
/// events of the BFS algorithm. Otherwise consider to use Bfs or bfs()
/// \tparam _Digraph The type of the digraph the algorithm runs on.
/// \ref ListDigraph. The value of _Digraph is not used directly by
/// \ref BfsVisit, it is only passed to \ref BfsVisitDefaultTraits.
/// \tparam _Visitor The Visitor type that is used by the algorithm.
/// \ref BfsVisitor "BfsVisitor<_Digraph>" is an empty visitor, which
/// does not observe the BFS events. If you want to observe the BFS
/// events, you should implement your own visitor class.
/// \tparam _Traits Traits class to set various data types used by the
/// algorithm. The default traits class is
/// \ref BfsVisitDefaultTraits "BfsVisitDefaultTraits<_Digraph>".
/// See \ref BfsVisitDefaultTraits for the documentation of
/// a BFS visit traits class.
template <typename _Digraph, typename _Visitor, typename _Traits>
template <typename _Digraph = ListDigraph,
typename _Visitor = BfsVisitor<_Digraph>,
typename _Traits = BfsVisitDefaultTraits<_Digraph> >
///The type of the digraph the algorithm runs on.
typedef typename Traits::Digraph Digraph;
///The visitor type used by the algorithm.
typedef _Visitor Visitor;
///The type of the map that indicates which nodes are reached.
typedef typename Traits::ReachedMap ReachedMap;
typedef typename Digraph::Node Node;
typedef typename Digraph::NodeIt NodeIt;
typedef typename Digraph::Arc Arc;
typedef typename Digraph::OutArcIt OutArcIt;
//Pointer to the underlying digraph.
//Pointer to the visitor object.
//Pointer to the map of reached status of the nodes.
//Indicates if _reached is locally allocated (true) or not.
std::vector<typename Digraph::Node> _list;
int _list_front, _list_back;
//Creates the maps if necessary.
_reached = Traits::createReachedMap(*_digraph);
/// \name Named Template Parameters
struct SetReachedMapTraits : public Traits {
static ReachedMap *createReachedMap(const Digraph &digraph) {
LEMON_ASSERT(false, "ReachedMap is not initialized");
return 0; // ignore warnings
/// \brief \ref named-templ-param "Named parameter" for setting
/// \ref named-templ-param "Named parameter" for setting ReachedMap type.
struct SetReachedMap : public BfsVisit< Digraph, Visitor,
SetReachedMapTraits<T> > {
typedef BfsVisit< Digraph, Visitor, SetReachedMapTraits<T> > Create;
/// \param digraph The digraph the algorithm runs on.
/// \param visitor The visitor object of the algorithm.
BfsVisit(const Digraph& digraph, Visitor& visitor)
: _digraph(&digraph), _visitor(&visitor),
_reached(0), local_reached(false) {}
if(local_reached) delete _reached;
/// \brief Sets the map that indicates which nodes are reached.
/// Sets the map that indicates which nodes are reached.
/// If you don't use this function before calling \ref run(Node) "run()"
/// or \ref init(), an instance will be allocated automatically.
/// The destructor deallocates this automatically allocated map,
/// \return <tt> (*this) </tt>
BfsVisit &reachedMap(ReachedMap &m) {
/// \name Execution Control
/// The simplest way to execute the BFS algorithm is to use one of the
/// member functions called \ref run(Node) "run()".\n
/// If you need more control on the execution, first you have to call
/// \ref init(), then you can add several source nodes with
/// \ref addSource(). Finally the actual path computation can be
/// performed with one of the \ref start() functions.
/// \brief Initializes the internal data structures.
/// Initializes the internal data structures.
_list.resize(countNodes(*_digraph));
_list_front = _list_back = -1;
for (NodeIt u(*_digraph) ; u != INVALID ; ++u) {
/// \brief Adds a new source node.
/// Adds a new source node to the set of nodes to be processed.
/// \brief Processes the next node.
/// Processes the next node.
/// \return The processed node.
/// \pre The queue must not be empty.
Node n = _list[++_list_front];
for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
Node m = _digraph->target(e);
/// \brief Processes the next node.
/// Processes the next node and checks if the given target node
/// is reached. If the target node is reachable from the processed
/// node, then the \c reach parameter will be set to \c true.
/// \param target The target node.
/// \retval reach Indicates if the target node is reached.
/// It should be initially \c false.
/// \return The processed node.
/// \pre The queue must not be empty.
Node processNextNode(Node target, bool& reach) {
Node n = _list[++_list_front];
for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
Node m = _digraph->target(e);
reach = reach || (target == m);
/// \brief Processes the next node.
/// Processes the next node and checks if at least one of reached
/// nodes has \c true value in the \c nm node map. If one node
/// with \c true value is reachable from the processed node, then the
/// \c rnode parameter will be set to the first of such nodes.
/// \param nm A \c bool (or convertible) node map that indicates the
/// \retval rnode The reached target node.
/// It should be initially \c INVALID.
/// \return The processed node.
/// \pre The queue must not be empty.
Node processNextNode(const NM& nm, Node& rnode) {
Node n = _list[++_list_front];
for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
Node m = _digraph->target(e);
if (nm[m] && rnode == INVALID) rnode = m;
/// \brief The next node to be processed.
/// Returns the next node to be processed or \c INVALID if the queue
return _list_front != _list_back ? _list[_list_front + 1] : INVALID;
/// \brief Returns \c false if there are nodes
/// Returns \c false if there are nodes
/// to be processed in the queue.
bool emptyQueue() const { return _list_front == _list_back; }
/// \brief Returns the number of the nodes to be processed.
/// Returns the number of the nodes to be processed in the queue.
int queueSize() const { return _list_back - _list_front; }
/// \brief Executes the algorithm.
/// Executes the algorithm.
/// This method runs the %BFS algorithm from the root node(s)
/// in order to compute the shortest path to each node.
/// The algorithm computes
/// - the shortest path tree (forest),
/// - the distance of each node from the root(s).
/// \pre init() must be called and at least one root node should be added
/// with addSource() before using this function.
/// \note <tt>b.start()</tt> is just a shortcut of the following code.
/// while ( !b.emptyQueue() ) {
while ( !emptyQueue() ) processNextNode();
/// \brief Executes the algorithm until the given target node is reached.
/// Executes the algorithm until the given target node is reached.
/// This method runs the %BFS algorithm from the root node(s)
/// in order to compute the shortest path to \c t.
/// The algorithm computes
/// - the shortest path to \c t,
/// - the distance of \c t from the root(s).
/// \pre init() must be called and at least one root node should be
/// added with addSource() before using this function.
/// \note <tt>b.start(t)</tt> is just a shortcut of the following code.
/// while ( !b.emptyQueue() && !reach ) {
/// b.processNextNode(t, reach);
while ( !emptyQueue() && !reach ) processNextNode(t, reach);
/// \brief Executes the algorithm until a condition is met.
/// Executes the algorithm until a condition is met.
/// This method runs the %BFS algorithm from the root node(s) in
/// order to compute the shortest path to a node \c v with
/// <tt>nm[v]</tt> true, if such a node can be found.
/// \param nm must be a bool (or convertible) node map. The
/// algorithm will stop when it reaches a node \c v with
/// \return The reached node \c v with <tt>nm[v]</tt> true or
/// \c INVALID if no such node was found.
/// \pre init() must be called and at least one root node should be
/// added with addSource() before using this function.
/// \note <tt>b.start(nm)</tt> is just a shortcut of the following code.
/// Node rnode = INVALID;
/// while ( !b.emptyQueue() && rnode == INVALID ) {
/// b.processNextNode(nm, rnode);
Node start(const NM &nm) {
while ( !emptyQueue() && rnode == INVALID ) {
processNextNode(nm, rnode);
/// \brief Runs the algorithm from the given source node.
/// This method runs the %BFS algorithm from node \c s
/// in order to compute the shortest path to each node.
/// The algorithm computes
/// - the shortest path tree,
/// - the distance of each node from the root.
/// \note <tt>b.run(s)</tt> is just a shortcut of the following code.
/// \brief Finds the shortest path between \c s and \c t.
/// This method runs the %BFS algorithm from node \c s
/// in order to compute the shortest path to node \c t
/// (it stops searching when \c t is processed).
/// \return \c true if \c t is reachable form \c s.
/// \note Apart from the return value, <tt>b.run(s,t)</tt> is just a
/// shortcut of the following code.
bool run(Node s,Node t) {
/// \brief Runs the algorithm to visit all nodes in the digraph.
/// This method runs the %BFS algorithm in order to
/// compute the shortest path to each node.
/// The algorithm computes
/// - the shortest path tree (forest),
/// - the distance of each node from the root(s).
/// \note <tt>b.run(s)</tt> is just a shortcut of the following code.
/// for (NodeIt n(gr); n != INVALID; ++n) {
for (NodeIt it(*_digraph); it != INVALID; ++it) {
/// \name Query Functions
/// The results of the BFS algorithm can be obtained using these
/// Either \ref run(Node) "run()" or \ref start() should be called
/// \brief Checks if a node is reached from the root(s).
/// Returns \c true if \c v is reached from the root(s).
/// \pre Either \ref run(Node) "run()" or \ref init()
/// must be called before using this function.
bool reached(Node v) const { return (*_reached)[v]; }
} //END OF NAMESPACE LEMON