COIN-OR::LEMON - Graph Library

source: lemon-1.2/lemon/bfs.h @ 497:47b376a5a2a7

Last change on this file since 497:47b376a5a2a7 was 301:9db8964f0cf6, checked in by Peter Kovacs <kpeter@…>, 16 years ago

Fix several doxygen warings

File size: 54.2 KB
RevLine 
[209]1/* -*- mode: C++; indent-tabs-mode: nil; -*-
[100]2 *
[209]3 * This file is a part of LEMON, a generic C++ optimization library.
[100]4 *
5 * Copyright (C) 2003-2008
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 *
9 * Permission to use, modify and distribute this software is granted
10 * provided that this copyright notice appears in all copies. For
11 * precise terms see the accompanying LICENSE file.
12 *
13 * This software is provided "AS IS" with no warranty of any kind,
14 * express or implied, and with no claim as to its suitability for any
15 * purpose.
16 *
17 */
18
19#ifndef LEMON_BFS_H
20#define LEMON_BFS_H
21
22///\ingroup search
23///\file
[244]24///\brief BFS algorithm.
[100]25
26#include <lemon/list_graph.h>
27#include <lemon/bits/path_dump.h>
[220]28#include <lemon/core.h>
[100]29#include <lemon/error.h>
30#include <lemon/maps.h>
[278]31#include <lemon/path.h>
[100]32
33namespace lemon {
34
35  ///Default traits class of Bfs class.
36
37  ///Default traits class of Bfs class.
[157]38  ///\tparam GR Digraph type.
[100]39  template<class GR>
40  struct BfsDefaultTraits
41  {
[244]42    ///The type of the digraph the algorithm runs on.
[100]43    typedef GR Digraph;
[244]44
45    ///\brief The type of the map that stores the predecessor
[100]46    ///arcs of the shortest paths.
[209]47    ///
[244]48    ///The type of the map that stores the predecessor
[100]49    ///arcs of the shortest paths.
50    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
[244]51    typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
[301]52    ///Instantiates a PredMap.
[209]53
[301]54    ///This function instantiates a PredMap.
[244]55    ///\param g is the digraph, to which we would like to define the
[301]56    ///PredMap.
[244]57    static PredMap *createPredMap(const Digraph &g)
[100]58    {
[244]59      return new PredMap(g);
[100]60    }
[244]61
[100]62    ///The type of the map that indicates which nodes are processed.
[209]63
[100]64    ///The type of the map that indicates which nodes are processed.
65    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
66    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
[301]67    ///Instantiates a ProcessedMap.
[209]68
[301]69    ///This function instantiates a ProcessedMap.
[100]70    ///\param g is the digraph, to which
[301]71    ///we would like to define the ProcessedMap
[100]72#ifdef DOXYGEN
[244]73    static ProcessedMap *createProcessedMap(const Digraph &g)
[100]74#else
[244]75    static ProcessedMap *createProcessedMap(const Digraph &)
[100]76#endif
77    {
78      return new ProcessedMap();
79    }
[244]80
[100]81    ///The type of the map that indicates which nodes are reached.
[209]82
[100]83    ///The type of the map that indicates which nodes are reached.
[244]84    ///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
[100]85    typedef typename Digraph::template NodeMap<bool> ReachedMap;
[301]86    ///Instantiates a ReachedMap.
[209]87
[301]88    ///This function instantiates a ReachedMap.
[244]89    ///\param g is the digraph, to which
[301]90    ///we would like to define the ReachedMap.
[244]91    static ReachedMap *createReachedMap(const Digraph &g)
[100]92    {
[244]93      return new ReachedMap(g);
[100]94    }
[209]95
[244]96    ///The type of the map that stores the distances of the nodes.
97
98    ///The type of the map that stores the distances of the nodes.
[100]99    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
100    typedef typename Digraph::template NodeMap<int> DistMap;
[301]101    ///Instantiates a DistMap.
[209]102
[301]103    ///This function instantiates a DistMap.
[244]104    ///\param g is the digraph, to which we would like to define the
[301]105    ///DistMap.
[244]106    static DistMap *createDistMap(const Digraph &g)
[100]107    {
[244]108      return new DistMap(g);
[100]109    }
110  };
[209]111
[100]112  ///%BFS algorithm class.
[209]113
[100]114  ///\ingroup search
115  ///This class provides an efficient implementation of the %BFS algorithm.
116  ///
[278]117  ///There is also a \ref bfs() "function-type interface" for the BFS
[244]118  ///algorithm, which is convenient in the simplier cases and it can be
119  ///used easier.
120  ///
121  ///\tparam GR The type of the digraph the algorithm runs on.
122  ///The default value is \ref ListDigraph. The value of GR is not used
123  ///directly by \ref Bfs, it is only passed to \ref BfsDefaultTraits.
[157]124  ///\tparam TR Traits class to set various data types used by the algorithm.
[100]125  ///The default traits class is
126  ///\ref BfsDefaultTraits "BfsDefaultTraits<GR>".
127  ///See \ref BfsDefaultTraits for the documentation of
128  ///a Bfs traits class.
129#ifdef DOXYGEN
130  template <typename GR,
[209]131            typename TR>
[100]132#else
133  template <typename GR=ListDigraph,
[209]134            typename TR=BfsDefaultTraits<GR> >
[100]135#endif
136  class Bfs {
137  public:
138
[244]139    ///The type of the digraph the algorithm runs on.
[100]140    typedef typename TR::Digraph Digraph;
[209]141
[244]142    ///\brief The type of the map that stores the predecessor arcs of the
143    ///shortest paths.
[100]144    typedef typename TR::PredMap PredMap;
[244]145    ///The type of the map that stores the distances of the nodes.
146    typedef typename TR::DistMap DistMap;
147    ///The type of the map that indicates which nodes are reached.
[100]148    typedef typename TR::ReachedMap ReachedMap;
[244]149    ///The type of the map that indicates which nodes are processed.
[100]150    typedef typename TR::ProcessedMap ProcessedMap;
[244]151    ///The type of the paths.
152    typedef PredMapPath<Digraph, PredMap> Path;
153
154    ///The traits class.
155    typedef TR Traits;
156
[100]157  private:
158
159    typedef typename Digraph::Node Node;
160    typedef typename Digraph::NodeIt NodeIt;
161    typedef typename Digraph::Arc Arc;
162    typedef typename Digraph::OutArcIt OutArcIt;
163
[244]164    //Pointer to the underlying digraph.
[100]165    const Digraph *G;
[244]166    //Pointer to the map of predecessor arcs.
[100]167    PredMap *_pred;
[244]168    //Indicates if _pred is locally allocated (true) or not.
[100]169    bool local_pred;
[244]170    //Pointer to the map of distances.
[100]171    DistMap *_dist;
[244]172    //Indicates if _dist is locally allocated (true) or not.
[100]173    bool local_dist;
[244]174    //Pointer to the map of reached status of the nodes.
[100]175    ReachedMap *_reached;
[244]176    //Indicates if _reached is locally allocated (true) or not.
[100]177    bool local_reached;
[244]178    //Pointer to the map of processed status of the nodes.
[100]179    ProcessedMap *_processed;
[244]180    //Indicates if _processed is locally allocated (true) or not.
[100]181    bool local_processed;
182
183    std::vector<typename Digraph::Node> _queue;
184    int _queue_head,_queue_tail,_queue_next_dist;
185    int _curr_dist;
186
[280]187    //Creates the maps if necessary.
[209]188    void create_maps()
[100]189    {
190      if(!_pred) {
[209]191        local_pred = true;
192        _pred = Traits::createPredMap(*G);
[100]193      }
194      if(!_dist) {
[209]195        local_dist = true;
196        _dist = Traits::createDistMap(*G);
[100]197      }
198      if(!_reached) {
[209]199        local_reached = true;
200        _reached = Traits::createReachedMap(*G);
[100]201      }
202      if(!_processed) {
[209]203        local_processed = true;
204        _processed = Traits::createProcessedMap(*G);
[100]205      }
206    }
207
208  protected:
[209]209
[100]210    Bfs() {}
[209]211
[100]212  public:
[209]213
[100]214    typedef Bfs Create;
215
216    ///\name Named template parameters
217
218    ///@{
219
220    template <class T>
[257]221    struct SetPredMapTraits : public Traits {
[100]222      typedef T PredMap;
[209]223      static PredMap *createPredMap(const Digraph &)
[100]224      {
[290]225        LEMON_ASSERT(false, "PredMap is not initialized");
226        return 0; // ignore warnings
[100]227      }
228    };
229    ///\brief \ref named-templ-param "Named parameter" for setting
[301]230    ///PredMap type.
[100]231    ///
[244]232    ///\ref named-templ-param "Named parameter" for setting
[301]233    ///PredMap type.
[100]234    template <class T>
[257]235    struct SetPredMap : public Bfs< Digraph, SetPredMapTraits<T> > {
236      typedef Bfs< Digraph, SetPredMapTraits<T> > Create;
[100]237    };
[209]238
[100]239    template <class T>
[257]240    struct SetDistMapTraits : public Traits {
[100]241      typedef T DistMap;
[209]242      static DistMap *createDistMap(const Digraph &)
[100]243      {
[290]244        LEMON_ASSERT(false, "DistMap is not initialized");
245        return 0; // ignore warnings
[100]246      }
247    };
248    ///\brief \ref named-templ-param "Named parameter" for setting
[301]249    ///DistMap type.
[100]250    ///
[244]251    ///\ref named-templ-param "Named parameter" for setting
[301]252    ///DistMap type.
[100]253    template <class T>
[257]254    struct SetDistMap : public Bfs< Digraph, SetDistMapTraits<T> > {
255      typedef Bfs< Digraph, SetDistMapTraits<T> > Create;
[100]256    };
[209]257
[100]258    template <class T>
[257]259    struct SetReachedMapTraits : public Traits {
[100]260      typedef T ReachedMap;
[209]261      static ReachedMap *createReachedMap(const Digraph &)
[100]262      {
[290]263        LEMON_ASSERT(false, "ReachedMap is not initialized");
264        return 0; // ignore warnings
[100]265      }
266    };
267    ///\brief \ref named-templ-param "Named parameter" for setting
[301]268    ///ReachedMap type.
[100]269    ///
[244]270    ///\ref named-templ-param "Named parameter" for setting
[301]271    ///ReachedMap type.
[100]272    template <class T>
[257]273    struct SetReachedMap : public Bfs< Digraph, SetReachedMapTraits<T> > {
274      typedef Bfs< Digraph, SetReachedMapTraits<T> > Create;
[100]275    };
[209]276
[100]277    template <class T>
[257]278    struct SetProcessedMapTraits : public Traits {
[100]279      typedef T ProcessedMap;
[209]280      static ProcessedMap *createProcessedMap(const Digraph &)
[100]281      {
[290]282        LEMON_ASSERT(false, "ProcessedMap is not initialized");
283        return 0; // ignore warnings
[100]284      }
285    };
286    ///\brief \ref named-templ-param "Named parameter" for setting
[301]287    ///ProcessedMap type.
[100]288    ///
[244]289    ///\ref named-templ-param "Named parameter" for setting
[301]290    ///ProcessedMap type.
[100]291    template <class T>
[257]292    struct SetProcessedMap : public Bfs< Digraph, SetProcessedMapTraits<T> > {
293      typedef Bfs< Digraph, SetProcessedMapTraits<T> > Create;
[100]294    };
[209]295
[257]296    struct SetStandardProcessedMapTraits : public Traits {
[100]297      typedef typename Digraph::template NodeMap<bool> ProcessedMap;
[244]298      static ProcessedMap *createProcessedMap(const Digraph &g)
[100]299      {
[244]300        return new ProcessedMap(g);
[290]301        return 0; // ignore warnings
[100]302      }
303    };
[244]304    ///\brief \ref named-templ-param "Named parameter" for setting
[301]305    ///ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
[100]306    ///
[244]307    ///\ref named-templ-param "Named parameter" for setting
[301]308    ///ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
[100]309    ///If you don't set it explicitly, it will be automatically allocated.
[257]310    struct SetStandardProcessedMap :
311      public Bfs< Digraph, SetStandardProcessedMapTraits > {
312      typedef Bfs< Digraph, SetStandardProcessedMapTraits > Create;
[100]313    };
[209]314
[100]315    ///@}
316
[209]317  public:
318
[100]319    ///Constructor.
[209]320
[244]321    ///Constructor.
322    ///\param g The digraph the algorithm runs on.
323    Bfs(const Digraph &g) :
324      G(&g),
[100]325      _pred(NULL), local_pred(false),
326      _dist(NULL), local_dist(false),
327      _reached(NULL), local_reached(false),
328      _processed(NULL), local_processed(false)
329    { }
[209]330
[100]331    ///Destructor.
[209]332    ~Bfs()
[100]333    {
334      if(local_pred) delete _pred;
335      if(local_dist) delete _dist;
336      if(local_reached) delete _reached;
337      if(local_processed) delete _processed;
338    }
339
[244]340    ///Sets the map that stores the predecessor arcs.
[100]341
[244]342    ///Sets the map that stores the predecessor arcs.
[100]343    ///If you don't use this function before calling \ref run(),
344    ///it will allocate one. The destructor deallocates this
345    ///automatically allocated map, of course.
346    ///\return <tt> (*this) </tt>
[209]347    Bfs &predMap(PredMap &m)
[100]348    {
349      if(local_pred) {
[209]350        delete _pred;
351        local_pred=false;
[100]352      }
353      _pred = &m;
354      return *this;
355    }
356
[244]357    ///Sets the map that indicates which nodes are reached.
[100]358
[244]359    ///Sets the map that indicates which nodes are reached.
[100]360    ///If you don't use this function before calling \ref run(),
361    ///it will allocate one. The destructor deallocates this
362    ///automatically allocated map, of course.
363    ///\return <tt> (*this) </tt>
[209]364    Bfs &reachedMap(ReachedMap &m)
[100]365    {
366      if(local_reached) {
[209]367        delete _reached;
368        local_reached=false;
[100]369      }
370      _reached = &m;
371      return *this;
372    }
373
[244]374    ///Sets the map that indicates which nodes are processed.
[100]375
[244]376    ///Sets the map that indicates which nodes are processed.
[100]377    ///If you don't use this function before calling \ref run(),
378    ///it will allocate one. The destructor deallocates this
379    ///automatically allocated map, of course.
380    ///\return <tt> (*this) </tt>
[209]381    Bfs &processedMap(ProcessedMap &m)
[100]382    {
383      if(local_processed) {
[209]384        delete _processed;
385        local_processed=false;
[100]386      }
387      _processed = &m;
388      return *this;
389    }
390
[244]391    ///Sets the map that stores the distances of the nodes.
[100]392
[244]393    ///Sets the map that stores the distances of the nodes calculated by
394    ///the algorithm.
[100]395    ///If you don't use this function before calling \ref run(),
396    ///it will allocate one. The destructor deallocates this
397    ///automatically allocated map, of course.
398    ///\return <tt> (*this) </tt>
[209]399    Bfs &distMap(DistMap &m)
[100]400    {
401      if(local_dist) {
[209]402        delete _dist;
403        local_dist=false;
[100]404      }
405      _dist = &m;
406      return *this;
407    }
408
409  public:
[244]410
[100]411    ///\name Execution control
412    ///The simplest way to execute the algorithm is to use
[244]413    ///one of the member functions called \ref lemon::Bfs::run() "run()".
[100]414    ///\n
[244]415    ///If you need more control on the execution, first you must call
416    ///\ref lemon::Bfs::init() "init()", then you can add several source
417    ///nodes with \ref lemon::Bfs::addSource() "addSource()".
418    ///Finally \ref lemon::Bfs::start() "start()" will perform the
419    ///actual path computation.
[100]420
421    ///@{
422
[244]423    ///Initializes the internal data structures.
424
[100]425    ///Initializes the internal data structures.
426    ///
427    void init()
428    {
429      create_maps();
430      _queue.resize(countNodes(*G));
431      _queue_head=_queue_tail=0;
432      _curr_dist=1;
433      for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
[209]434        _pred->set(u,INVALID);
435        _reached->set(u,false);
436        _processed->set(u,false);
[100]437      }
438    }
[209]439
[100]440    ///Adds a new source node.
441
442    ///Adds a new source node to the set of nodes to be processed.
443    ///
444    void addSource(Node s)
445    {
446      if(!(*_reached)[s])
[209]447        {
448          _reached->set(s,true);
449          _pred->set(s,INVALID);
450          _dist->set(s,0);
451          _queue[_queue_head++]=s;
452          _queue_next_dist=_queue_head;
453        }
[100]454    }
[209]455
[100]456    ///Processes the next node.
457
458    ///Processes the next node.
459    ///
460    ///\return The processed node.
461    ///
[244]462    ///\pre The queue must not be empty.
[100]463    Node processNextNode()
464    {
465      if(_queue_tail==_queue_next_dist) {
[209]466        _curr_dist++;
467        _queue_next_dist=_queue_head;
[100]468      }
469      Node n=_queue[_queue_tail++];
470      _processed->set(n,true);
471      Node m;
472      for(OutArcIt e(*G,n);e!=INVALID;++e)
[209]473        if(!(*_reached)[m=G->target(e)]) {
474          _queue[_queue_head++]=m;
475          _reached->set(m,true);
476          _pred->set(m,e);
477          _dist->set(m,_curr_dist);
478        }
[100]479      return n;
480    }
481
482    ///Processes the next node.
483
[244]484    ///Processes the next node and checks if the given target node
[100]485    ///is reached. If the target node is reachable from the processed
[244]486    ///node, then the \c reach parameter will be set to \c true.
[100]487    ///
488    ///\param target The target node.
[244]489    ///\retval reach Indicates if the target node is reached.
490    ///It should be initially \c false.
491    ///
[100]492    ///\return The processed node.
493    ///
[244]494    ///\pre The queue must not be empty.
[100]495    Node processNextNode(Node target, bool& reach)
496    {
497      if(_queue_tail==_queue_next_dist) {
[209]498        _curr_dist++;
499        _queue_next_dist=_queue_head;
[100]500      }
501      Node n=_queue[_queue_tail++];
502      _processed->set(n,true);
503      Node m;
504      for(OutArcIt e(*G,n);e!=INVALID;++e)
[209]505        if(!(*_reached)[m=G->target(e)]) {
506          _queue[_queue_head++]=m;
507          _reached->set(m,true);
508          _pred->set(m,e);
509          _dist->set(m,_curr_dist);
[100]510          reach = reach || (target == m);
[209]511        }
[100]512      return n;
513    }
514
515    ///Processes the next node.
516
[244]517    ///Processes the next node and checks if at least one of reached
518    ///nodes has \c true value in the \c nm node map. If one node
519    ///with \c true value is reachable from the processed node, then the
520    ///\c rnode parameter will be set to the first of such nodes.
[100]521    ///
[244]522    ///\param nm A \c bool (or convertible) node map that indicates the
523    ///possible targets.
[100]524    ///\retval rnode The reached target node.
[244]525    ///It should be initially \c INVALID.
526    ///
[100]527    ///\return The processed node.
528    ///
[244]529    ///\pre The queue must not be empty.
[100]530    template<class NM>
531    Node processNextNode(const NM& nm, Node& rnode)
532    {
533      if(_queue_tail==_queue_next_dist) {
[209]534        _curr_dist++;
535        _queue_next_dist=_queue_head;
[100]536      }
537      Node n=_queue[_queue_tail++];
538      _processed->set(n,true);
539      Node m;
540      for(OutArcIt e(*G,n);e!=INVALID;++e)
[209]541        if(!(*_reached)[m=G->target(e)]) {
542          _queue[_queue_head++]=m;
543          _reached->set(m,true);
544          _pred->set(m,e);
545          _dist->set(m,_curr_dist);
546          if (nm[m] && rnode == INVALID) rnode = m;
547        }
[100]548      return n;
549    }
[209]550
[244]551    ///The next node to be processed.
[100]552
[244]553    ///Returns the next node to be processed or \c INVALID if the queue
554    ///is empty.
555    Node nextNode() const
[209]556    {
[100]557      return _queue_tail<_queue_head?_queue[_queue_tail]:INVALID;
558    }
[209]559
[100]560    ///\brief Returns \c false if there are nodes
[244]561    ///to be processed.
[100]562    ///
563    ///Returns \c false if there are nodes
[244]564    ///to be processed in the queue.
565    bool emptyQueue() const { return _queue_tail==_queue_head; }
566
[100]567    ///Returns the number of the nodes to be processed.
[209]568
[100]569    ///Returns the number of the nodes to be processed in the queue.
[244]570    int queueSize() const { return _queue_head-_queue_tail; }
[209]571
[100]572    ///Executes the algorithm.
573
574    ///Executes the algorithm.
575    ///
[244]576    ///This method runs the %BFS algorithm from the root node(s)
577    ///in order to compute the shortest path to each node.
[100]578    ///
[244]579    ///The algorithm computes
580    ///- the shortest path tree (forest),
581    ///- the distance of each node from the root(s).
582    ///
583    ///\pre init() must be called and at least one root node should be
584    ///added with addSource() before using this function.
585    ///
586    ///\note <tt>b.start()</tt> is just a shortcut of the following code.
587    ///\code
588    ///  while ( !b.emptyQueue() ) {
589    ///    b.processNextNode();
590    ///  }
591    ///\endcode
[100]592    void start()
593    {
594      while ( !emptyQueue() ) processNextNode();
595    }
[209]596
[244]597    ///Executes the algorithm until the given target node is reached.
[100]598
[244]599    ///Executes the algorithm until the given target node is reached.
[100]600    ///
601    ///This method runs the %BFS algorithm from the root node(s)
[286]602    ///in order to compute the shortest path to \c t.
[244]603    ///
[100]604    ///The algorithm computes
[286]605    ///- the shortest path to \c t,
606    ///- the distance of \c t from the root(s).
[244]607    ///
608    ///\pre init() must be called and at least one root node should be
609    ///added with addSource() before using this function.
610    ///
611    ///\note <tt>b.start(t)</tt> is just a shortcut of the following code.
612    ///\code
613    ///  bool reach = false;
614    ///  while ( !b.emptyQueue() && !reach ) {
615    ///    b.processNextNode(t, reach);
616    ///  }
617    ///\endcode
[286]618    void start(Node t)
[100]619    {
620      bool reach = false;
[286]621      while ( !emptyQueue() && !reach ) processNextNode(t, reach);
[100]622    }
[209]623
[100]624    ///Executes the algorithm until a condition is met.
625
626    ///Executes the algorithm until a condition is met.
627    ///
[244]628    ///This method runs the %BFS algorithm from the root node(s) in
629    ///order to compute the shortest path to a node \c v with
630    /// <tt>nm[v]</tt> true, if such a node can be found.
[100]631    ///
[244]632    ///\param nm A \c bool (or convertible) node map. The algorithm
633    ///will stop when it reaches a node \c v with <tt>nm[v]</tt> true.
[100]634    ///
635    ///\return The reached node \c v with <tt>nm[v]</tt> true or
636    ///\c INVALID if no such node was found.
[244]637    ///
638    ///\pre init() must be called and at least one root node should be
639    ///added with addSource() before using this function.
640    ///
641    ///\note <tt>b.start(nm)</tt> is just a shortcut of the following code.
642    ///\code
643    ///  Node rnode = INVALID;
644    ///  while ( !b.emptyQueue() && rnode == INVALID ) {
645    ///    b.processNextNode(nm, rnode);
646    ///  }
647    ///  return rnode;
648    ///\endcode
649    template<class NodeBoolMap>
650    Node start(const NodeBoolMap &nm)
[100]651    {
652      Node rnode = INVALID;
653      while ( !emptyQueue() && rnode == INVALID ) {
[209]654        processNextNode(nm, rnode);
[100]655      }
656      return rnode;
657    }
[209]658
[286]659    ///Runs the algorithm from the given source node.
[209]660
[244]661    ///This method runs the %BFS algorithm from node \c s
662    ///in order to compute the shortest path to each node.
[100]663    ///
[244]664    ///The algorithm computes
665    ///- the shortest path tree,
666    ///- the distance of each node from the root.
667    ///
668    ///\note <tt>b.run(s)</tt> is just a shortcut of the following code.
[100]669    ///\code
670    ///  b.init();
671    ///  b.addSource(s);
672    ///  b.start();
673    ///\endcode
674    void run(Node s) {
675      init();
676      addSource(s);
677      start();
678    }
[209]679
[100]680    ///Finds the shortest path between \c s and \c t.
[209]681
[244]682    ///This method runs the %BFS algorithm from node \c s
[286]683    ///in order to compute the shortest path to node \c t
684    ///(it stops searching when \c t is processed).
[100]685    ///
[286]686    ///\return \c true if \c t is reachable form \c s.
[244]687    ///
688    ///\note Apart from the return value, <tt>b.run(s,t)</tt> is just a
689    ///shortcut of the following code.
[100]690    ///\code
691    ///  b.init();
692    ///  b.addSource(s);
693    ///  b.start(t);
694    ///\endcode
[286]695    bool run(Node s,Node t) {
[100]696      init();
697      addSource(s);
698      start(t);
[286]699      return reached(t);
[100]700    }
[209]701
[244]702    ///Runs the algorithm to visit all nodes in the digraph.
703
704    ///This method runs the %BFS algorithm in order to
705    ///compute the shortest path to each node.
706    ///
707    ///The algorithm computes
708    ///- the shortest path tree (forest),
709    ///- the distance of each node from the root(s).
710    ///
711    ///\note <tt>b.run(s)</tt> is just a shortcut of the following code.
712    ///\code
713    ///  b.init();
714    ///  for (NodeIt n(gr); n != INVALID; ++n) {
715    ///    if (!b.reached(n)) {
716    ///      b.addSource(n);
717    ///      b.start();
718    ///    }
719    ///  }
720    ///\endcode
721    void run() {
722      init();
723      for (NodeIt n(*G); n != INVALID; ++n) {
724        if (!reached(n)) {
725          addSource(n);
726          start();
727        }
728      }
729    }
730
[100]731    ///@}
732
733    ///\name Query Functions
734    ///The result of the %BFS algorithm can be obtained using these
735    ///functions.\n
[244]736    ///Either \ref lemon::Bfs::run() "run()" or \ref lemon::Bfs::start()
737    ///"start()" must be called before using them.
[209]738
[100]739    ///@{
740
[244]741    ///The shortest path to a node.
[100]742
[244]743    ///Returns the shortest path to a node.
744    ///
745    ///\warning \c t should be reachable from the root(s).
746    ///
747    ///\pre Either \ref run() or \ref start() must be called before
748    ///using this function.
749    Path path(Node t) const { return Path(*G, *_pred, t); }
[100]750
751    ///The distance of a node from the root(s).
752
753    ///Returns the distance of a node from the root(s).
[244]754    ///
755    ///\warning If node \c v is not reachable from the root(s), then
756    ///the return value of this function is undefined.
757    ///
758    ///\pre Either \ref run() or \ref start() must be called before
759    ///using this function.
[100]760    int dist(Node v) const { return (*_dist)[v]; }
761
[244]762    ///Returns the 'previous arc' of the shortest path tree for a node.
[100]763
[244]764    ///This function returns the 'previous arc' of the shortest path
765    ///tree for the node \c v, i.e. it returns the last arc of a
766    ///shortest path from the root(s) to \c v. It is \c INVALID if \c v
767    ///is not reachable from the root(s) or if \c v is a root.
768    ///
769    ///The shortest path tree used here is equal to the shortest path
770    ///tree used in \ref predNode().
771    ///
772    ///\pre Either \ref run() or \ref start() must be called before
773    ///using this function.
[100]774    Arc predArc(Node v) const { return (*_pred)[v];}
775
[244]776    ///Returns the 'previous node' of the shortest path tree for a node.
[100]777
[244]778    ///This function returns the 'previous node' of the shortest path
779    ///tree for the node \c v, i.e. it returns the last but one node
780    ///from a shortest path from the root(s) to \c v. It is \c INVALID
781    ///if \c v is not reachable from the root(s) or if \c v is a root.
782    ///
[100]783    ///The shortest path tree used here is equal to the shortest path
784    ///tree used in \ref predArc().
[244]785    ///
[100]786    ///\pre Either \ref run() or \ref start() must be called before
787    ///using this function.
788    Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
[209]789                                  G->source((*_pred)[v]); }
790
[244]791    ///\brief Returns a const reference to the node map that stores the
792    /// distances of the nodes.
793    ///
794    ///Returns a const reference to the node map that stores the distances
795    ///of the nodes calculated by the algorithm.
796    ///
797    ///\pre Either \ref run() or \ref init()
798    ///must be called before using this function.
[100]799    const DistMap &distMap() const { return *_dist;}
[209]800
[244]801    ///\brief Returns a const reference to the node map that stores the
802    ///predecessor arcs.
803    ///
804    ///Returns a const reference to the node map that stores the predecessor
805    ///arcs, which form the shortest path tree.
806    ///
[100]807    ///\pre Either \ref run() or \ref init()
808    ///must be called before using this function.
809    const PredMap &predMap() const { return *_pred;}
[209]810
[244]811    ///Checks if a node is reachable from the root(s).
[100]812
[244]813    ///Returns \c true if \c v is reachable from the root(s).
[100]814    ///\pre Either \ref run() or \ref start()
815    ///must be called before using this function.
[244]816    bool reached(Node v) const { return (*_reached)[v]; }
[209]817
[100]818    ///@}
819  };
820
[244]821  ///Default traits class of bfs() function.
[100]822
[244]823  ///Default traits class of bfs() function.
[157]824  ///\tparam GR Digraph type.
[100]825  template<class GR>
826  struct BfsWizardDefaultTraits
827  {
[244]828    ///The type of the digraph the algorithm runs on.
[100]829    typedef GR Digraph;
[244]830
831    ///\brief The type of the map that stores the predecessor
[100]832    ///arcs of the shortest paths.
[209]833    ///
[244]834    ///The type of the map that stores the predecessor
[100]835    ///arcs of the shortest paths.
836    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
[278]837    typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
[301]838    ///Instantiates a PredMap.
[209]839
[301]840    ///This function instantiates a PredMap.
[244]841    ///\param g is the digraph, to which we would like to define the
[301]842    ///PredMap.
[244]843    static PredMap *createPredMap(const Digraph &g)
[100]844    {
[278]845      return new PredMap(g);
[100]846    }
847
848    ///The type of the map that indicates which nodes are processed.
[209]849
[100]850    ///The type of the map that indicates which nodes are processed.
851    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
[278]852    ///By default it is a NullMap.
[100]853    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
[301]854    ///Instantiates a ProcessedMap.
[209]855
[301]856    ///This function instantiates a ProcessedMap.
[100]857    ///\param g is the digraph, to which
[301]858    ///we would like to define the ProcessedMap.
[100]859#ifdef DOXYGEN
[244]860    static ProcessedMap *createProcessedMap(const Digraph &g)
[100]861#else
[244]862    static ProcessedMap *createProcessedMap(const Digraph &)
[100]863#endif
864    {
865      return new ProcessedMap();
866    }
[244]867
[100]868    ///The type of the map that indicates which nodes are reached.
[209]869
[100]870    ///The type of the map that indicates which nodes are reached.
[244]871    ///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
[100]872    typedef typename Digraph::template NodeMap<bool> ReachedMap;
[301]873    ///Instantiates a ReachedMap.
[209]874
[301]875    ///This function instantiates a ReachedMap.
[244]876    ///\param g is the digraph, to which
[301]877    ///we would like to define the ReachedMap.
[244]878    static ReachedMap *createReachedMap(const Digraph &g)
[100]879    {
[244]880      return new ReachedMap(g);
[100]881    }
[209]882
[244]883    ///The type of the map that stores the distances of the nodes.
884
885    ///The type of the map that stores the distances of the nodes.
[100]886    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
[278]887    typedef typename Digraph::template NodeMap<int> DistMap;
[301]888    ///Instantiates a DistMap.
[209]889
[301]890    ///This function instantiates a DistMap.
[210]891    ///\param g is the digraph, to which we would like to define
[301]892    ///the DistMap
[244]893    static DistMap *createDistMap(const Digraph &g)
[100]894    {
[278]895      return new DistMap(g);
[100]896    }
[278]897
898    ///The type of the shortest paths.
899
900    ///The type of the shortest paths.
901    ///It must meet the \ref concepts::Path "Path" concept.
902    typedef lemon::Path<Digraph> Path;
[100]903  };
[209]904
[301]905  /// Default traits class used by BfsWizard
[100]906
907  /// To make it easier to use Bfs algorithm
[244]908  /// we have created a wizard class.
[100]909  /// This \ref BfsWizard class needs default traits,
[244]910  /// as well as the \ref Bfs class.
[100]911  /// The \ref BfsWizardBase is a class to be the default traits of the
912  /// \ref BfsWizard class.
913  template<class GR>
914  class BfsWizardBase : public BfsWizardDefaultTraits<GR>
915  {
916
917    typedef BfsWizardDefaultTraits<GR> Base;
918  protected:
[244]919    //The type of the nodes in the digraph.
[100]920    typedef typename Base::Digraph::Node Node;
921
[244]922    //Pointer to the digraph the algorithm runs on.
[100]923    void *_g;
[244]924    //Pointer to the map of reached nodes.
[100]925    void *_reached;
[244]926    //Pointer to the map of processed nodes.
[100]927    void *_processed;
[244]928    //Pointer to the map of predecessors arcs.
[100]929    void *_pred;
[244]930    //Pointer to the map of distances.
[100]931    void *_dist;
[278]932    //Pointer to the shortest path to the target node.
933    void *_path;
934    //Pointer to the distance of the target node.
935    int *_di;
[209]936
[100]937    public:
938    /// Constructor.
[209]939
[100]940    /// This constructor does not require parameters, therefore it initiates
[278]941    /// all of the attributes to \c 0.
[100]942    BfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0),
[278]943                      _dist(0), _path(0), _di(0) {}
[100]944
945    /// Constructor.
[209]946
[278]947    /// This constructor requires one parameter,
948    /// others are initiated to \c 0.
[244]949    /// \param g The digraph the algorithm runs on.
[278]950    BfsWizardBase(const GR &g) :
[209]951      _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
[278]952      _reached(0), _processed(0), _pred(0), _dist(0),  _path(0), _di(0) {}
[100]953
954  };
[209]955
[278]956  /// Auxiliary class for the function-type interface of BFS algorithm.
[100]957
[278]958  /// This auxiliary class is created to implement the
959  /// \ref bfs() "function-type interface" of \ref Bfs algorithm.
960  /// It does not have own \ref run() method, it uses the functions
961  /// and features of the plain \ref Bfs.
[100]962  ///
[278]963  /// This class should only be used through the \ref bfs() function,
964  /// which makes it easier to use the algorithm.
[100]965  template<class TR>
966  class BfsWizard : public TR
967  {
968    typedef TR Base;
969
[244]970    ///The type of the digraph the algorithm runs on.
[100]971    typedef typename TR::Digraph Digraph;
[244]972
[100]973    typedef typename Digraph::Node Node;
974    typedef typename Digraph::NodeIt NodeIt;
975    typedef typename Digraph::Arc Arc;
976    typedef typename Digraph::OutArcIt OutArcIt;
[209]977
[244]978    ///\brief The type of the map that stores the predecessor
[100]979    ///arcs of the shortest paths.
980    typedef typename TR::PredMap PredMap;
[244]981    ///\brief The type of the map that stores the distances of the nodes.
[100]982    typedef typename TR::DistMap DistMap;
[244]983    ///\brief The type of the map that indicates which nodes are reached.
984    typedef typename TR::ReachedMap ReachedMap;
985    ///\brief The type of the map that indicates which nodes are processed.
986    typedef typename TR::ProcessedMap ProcessedMap;
[278]987    ///The type of the shortest paths
988    typedef typename TR::Path Path;
[100]989
990  public:
[244]991
[100]992    /// Constructor.
993    BfsWizard() : TR() {}
994
995    /// Constructor that requires parameters.
996
997    /// Constructor that requires parameters.
998    /// These parameters will be the default values for the traits class.
[278]999    /// \param g The digraph the algorithm runs on.
1000    BfsWizard(const Digraph &g) :
1001      TR(g) {}
[100]1002
1003    ///Copy constructor
1004    BfsWizard(const TR &b) : TR(b) {}
1005
1006    ~BfsWizard() {}
1007
[278]1008    ///Runs BFS algorithm from the given source node.
[209]1009
[278]1010    ///This method runs BFS algorithm from node \c s
1011    ///in order to compute the shortest path to each node.
1012    void run(Node s)
1013    {
1014      Bfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
1015      if (Base::_pred)
1016        alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1017      if (Base::_dist)
1018        alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1019      if (Base::_reached)
1020        alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
1021      if (Base::_processed)
1022        alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1023      if (s!=INVALID)
1024        alg.run(s);
1025      else
1026        alg.run();
1027    }
1028
1029    ///Finds the shortest path between \c s and \c t.
1030
1031    ///This method runs BFS algorithm from node \c s
1032    ///in order to compute the shortest path to node \c t
1033    ///(it stops searching when \c t is processed).
1034    ///
1035    ///\return \c true if \c t is reachable form \c s.
1036    bool run(Node s, Node t)
1037    {
1038      Bfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
1039      if (Base::_pred)
1040        alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1041      if (Base::_dist)
1042        alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1043      if (Base::_reached)
1044        alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
1045      if (Base::_processed)
1046        alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1047      alg.run(s,t);
1048      if (Base::_path)
1049        *reinterpret_cast<Path*>(Base::_path) = alg.path(t);
1050      if (Base::_di)
1051        *Base::_di = alg.dist(t);
1052      return alg.reached(t);
1053    }
1054
1055    ///Runs BFS algorithm to visit all nodes in the digraph.
1056
1057    ///This method runs BFS algorithm in order to compute
1058    ///the shortest path to each node.
[100]1059    void run()
1060    {
[278]1061      run(INVALID);
[100]1062    }
[209]1063
[244]1064    template<class T>
[257]1065    struct SetPredMapBase : public Base {
[244]1066      typedef T PredMap;
1067      static PredMap *createPredMap(const Digraph &) { return 0; };
[257]1068      SetPredMapBase(const TR &b) : TR(b) {}
[244]1069    };
[278]1070    ///\brief \ref named-func-param "Named parameter"
[301]1071    ///for setting PredMap object.
[244]1072    ///
[278]1073    ///\ref named-func-param "Named parameter"
[301]1074    ///for setting PredMap object.
[244]1075    template<class T>
[257]1076    BfsWizard<SetPredMapBase<T> > predMap(const T &t)
[244]1077    {
1078      Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
[257]1079      return BfsWizard<SetPredMapBase<T> >(*this);
[244]1080    }
1081
1082    template<class T>
[257]1083    struct SetReachedMapBase : public Base {
[244]1084      typedef T ReachedMap;
1085      static ReachedMap *createReachedMap(const Digraph &) { return 0; };
[257]1086      SetReachedMapBase(const TR &b) : TR(b) {}
[244]1087    };
[278]1088    ///\brief \ref named-func-param "Named parameter"
[301]1089    ///for setting ReachedMap object.
[244]1090    ///
[278]1091    /// \ref named-func-param "Named parameter"
[301]1092    ///for setting ReachedMap object.
[244]1093    template<class T>
[257]1094    BfsWizard<SetReachedMapBase<T> > reachedMap(const T &t)
[244]1095    {
1096      Base::_reached=reinterpret_cast<void*>(const_cast<T*>(&t));
[257]1097      return BfsWizard<SetReachedMapBase<T> >(*this);
[244]1098    }
1099
1100    template<class T>
[278]1101    struct SetDistMapBase : public Base {
1102      typedef T DistMap;
1103      static DistMap *createDistMap(const Digraph &) { return 0; };
1104      SetDistMapBase(const TR &b) : TR(b) {}
1105    };
1106    ///\brief \ref named-func-param "Named parameter"
[301]1107    ///for setting DistMap object.
[278]1108    ///
1109    /// \ref named-func-param "Named parameter"
[301]1110    ///for setting DistMap object.
[278]1111    template<class T>
1112    BfsWizard<SetDistMapBase<T> > distMap(const T &t)
1113    {
1114      Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1115      return BfsWizard<SetDistMapBase<T> >(*this);
1116    }
1117
1118    template<class T>
[257]1119    struct SetProcessedMapBase : public Base {
[244]1120      typedef T ProcessedMap;
1121      static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
[257]1122      SetProcessedMapBase(const TR &b) : TR(b) {}
[244]1123    };
[278]1124    ///\brief \ref named-func-param "Named parameter"
[301]1125    ///for setting ProcessedMap object.
[244]1126    ///
[278]1127    /// \ref named-func-param "Named parameter"
[301]1128    ///for setting ProcessedMap object.
[244]1129    template<class T>
[257]1130    BfsWizard<SetProcessedMapBase<T> > processedMap(const T &t)
[244]1131    {
1132      Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
[257]1133      return BfsWizard<SetProcessedMapBase<T> >(*this);
[244]1134    }
1135
1136    template<class T>
[278]1137    struct SetPathBase : public Base {
1138      typedef T Path;
1139      SetPathBase(const TR &b) : TR(b) {}
[244]1140    };
[278]1141    ///\brief \ref named-func-param "Named parameter"
1142    ///for getting the shortest path to the target node.
[244]1143    ///
[278]1144    ///\ref named-func-param "Named parameter"
1145    ///for getting the shortest path to the target node.
[244]1146    template<class T>
[278]1147    BfsWizard<SetPathBase<T> > path(const T &t)
[244]1148    {
[278]1149      Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t));
1150      return BfsWizard<SetPathBase<T> >(*this);
1151    }
1152
1153    ///\brief \ref named-func-param "Named parameter"
1154    ///for getting the distance of the target node.
1155    ///
1156    ///\ref named-func-param "Named parameter"
1157    ///for getting the distance of the target node.
1158    BfsWizard dist(const int &d)
1159    {
1160      Base::_di=const_cast<int*>(&d);
1161      return *this;
[244]1162    }
1163
[100]1164  };
[209]1165
[278]1166  ///Function-type interface for BFS algorithm.
[100]1167
1168  /// \ingroup search
[278]1169  ///Function-type interface for BFS algorithm.
[100]1170  ///
[278]1171  ///This function also has several \ref named-func-param "named parameters",
[100]1172  ///they are declared as the members of class \ref BfsWizard.
[278]1173  ///The following examples show how to use these parameters.
[100]1174  ///\code
[278]1175  ///  // Compute shortest path from node s to each node
1176  ///  bfs(g).predMap(preds).distMap(dists).run(s);
1177  ///
1178  ///  // Compute shortest path from s to t
1179  ///  bool reached = bfs(g).path(p).dist(d).run(s,t);
[100]1180  ///\endcode
1181  ///\warning Don't forget to put the \ref BfsWizard::run() "run()"
1182  ///to the end of the parameter list.
1183  ///\sa BfsWizard
1184  ///\sa Bfs
1185  template<class GR>
1186  BfsWizard<BfsWizardBase<GR> >
[278]1187  bfs(const GR &digraph)
[100]1188  {
[278]1189    return BfsWizard<BfsWizardBase<GR> >(digraph);
[100]1190  }
1191
1192#ifdef DOXYGEN
[244]1193  /// \brief Visitor class for BFS.
[209]1194  ///
[100]1195  /// This class defines the interface of the BfsVisit events, and
[244]1196  /// it could be the base of a real visitor class.
[100]1197  template <typename _Digraph>
1198  struct BfsVisitor {
1199    typedef _Digraph Digraph;
1200    typedef typename Digraph::Arc Arc;
1201    typedef typename Digraph::Node Node;
[244]1202    /// \brief Called for the source node(s) of the BFS.
[209]1203    ///
[244]1204    /// This function is called for the source node(s) of the BFS.
1205    void start(const Node& node) {}
1206    /// \brief Called when a node is reached first time.
1207    ///
1208    /// This function is called when a node is reached first time.
1209    void reach(const Node& node) {}
1210    /// \brief Called when a node is processed.
1211    ///
1212    /// This function is called when a node is processed.
1213    void process(const Node& node) {}
1214    /// \brief Called when an arc reaches a new node.
1215    ///
1216    /// This function is called when the BFS finds an arc whose target node
1217    /// is not reached yet.
[100]1218    void discover(const Arc& arc) {}
[244]1219    /// \brief Called when an arc is examined but its target node is
[100]1220    /// already discovered.
[209]1221    ///
[244]1222    /// This function is called when an arc is examined but its target node is
[100]1223    /// already discovered.
1224    void examine(const Arc& arc) {}
1225  };
1226#else
1227  template <typename _Digraph>
1228  struct BfsVisitor {
1229    typedef _Digraph Digraph;
1230    typedef typename Digraph::Arc Arc;
1231    typedef typename Digraph::Node Node;
[244]1232    void start(const Node&) {}
1233    void reach(const Node&) {}
1234    void process(const Node&) {}
[100]1235    void discover(const Arc&) {}
1236    void examine(const Arc&) {}
1237
1238    template <typename _Visitor>
1239    struct Constraints {
1240      void constraints() {
[209]1241        Arc arc;
1242        Node node;
[244]1243        visitor.start(node);
1244        visitor.reach(node);
1245        visitor.process(node);
[209]1246        visitor.discover(arc);
1247        visitor.examine(arc);
[100]1248      }
1249      _Visitor& visitor;
1250    };
1251  };
1252#endif
1253
1254  /// \brief Default traits class of BfsVisit class.
1255  ///
1256  /// Default traits class of BfsVisit class.
[244]1257  /// \tparam _Digraph The type of the digraph the algorithm runs on.
[100]1258  template<class _Digraph>
1259  struct BfsVisitDefaultTraits {
1260
[244]1261    /// \brief The type of the digraph the algorithm runs on.
[100]1262    typedef _Digraph Digraph;
1263
1264    /// \brief The type of the map that indicates which nodes are reached.
[209]1265    ///
[100]1266    /// The type of the map that indicates which nodes are reached.
[244]1267    /// It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
[100]1268    typedef typename Digraph::template NodeMap<bool> ReachedMap;
1269
[301]1270    /// \brief Instantiates a ReachedMap.
[100]1271    ///
[301]1272    /// This function instantiates a ReachedMap.
[100]1273    /// \param digraph is the digraph, to which
[301]1274    /// we would like to define the ReachedMap.
[100]1275    static ReachedMap *createReachedMap(const Digraph &digraph) {
1276      return new ReachedMap(digraph);
1277    }
1278
1279  };
1280
1281  /// \ingroup search
[209]1282  ///
[244]1283  /// \brief %BFS algorithm class with visitor interface.
[209]1284  ///
[100]1285  /// This class provides an efficient implementation of the %BFS algorithm
1286  /// with visitor interface.
1287  ///
1288  /// The %BfsVisit class provides an alternative interface to the Bfs
1289  /// class. It works with callback mechanism, the BfsVisit object calls
[244]1290  /// the member functions of the \c Visitor class on every BFS event.
[100]1291  ///
[252]1292  /// This interface of the BFS algorithm should be used in special cases
1293  /// when extra actions have to be performed in connection with certain
1294  /// events of the BFS algorithm. Otherwise consider to use Bfs or bfs()
1295  /// instead.
1296  ///
[244]1297  /// \tparam _Digraph The type of the digraph the algorithm runs on.
[210]1298  /// The default value is
[244]1299  /// \ref ListDigraph. The value of _Digraph is not used directly by
1300  /// \ref BfsVisit, it is only passed to \ref BfsVisitDefaultTraits.
1301  /// \tparam _Visitor The Visitor type that is used by the algorithm.
1302  /// \ref BfsVisitor "BfsVisitor<_Digraph>" is an empty visitor, which
1303  /// does not observe the BFS events. If you want to observe the BFS
1304  /// events, you should implement your own visitor class.
[209]1305  /// \tparam _Traits Traits class to set various data types used by the
[100]1306  /// algorithm. The default traits class is
1307  /// \ref BfsVisitDefaultTraits "BfsVisitDefaultTraits<_Digraph>".
1308  /// See \ref BfsVisitDefaultTraits for the documentation of
[244]1309  /// a BFS visit traits class.
[100]1310#ifdef DOXYGEN
1311  template <typename _Digraph, typename _Visitor, typename _Traits>
1312#else
1313  template <typename _Digraph = ListDigraph,
[209]1314            typename _Visitor = BfsVisitor<_Digraph>,
[288]1315            typename _Traits = BfsVisitDefaultTraits<_Digraph> >
[100]1316#endif
1317  class BfsVisit {
1318  public:
[209]1319
[244]1320    ///The traits class.
[100]1321    typedef _Traits Traits;
1322
[244]1323    ///The type of the digraph the algorithm runs on.
[100]1324    typedef typename Traits::Digraph Digraph;
1325
[244]1326    ///The visitor type used by the algorithm.
[100]1327    typedef _Visitor Visitor;
1328
[244]1329    ///The type of the map that indicates which nodes are reached.
[100]1330    typedef typename Traits::ReachedMap ReachedMap;
1331
1332  private:
1333
1334    typedef typename Digraph::Node Node;
1335    typedef typename Digraph::NodeIt NodeIt;
1336    typedef typename Digraph::Arc Arc;
1337    typedef typename Digraph::OutArcIt OutArcIt;
1338
[244]1339    //Pointer to the underlying digraph.
[100]1340    const Digraph *_digraph;
[244]1341    //Pointer to the visitor object.
[100]1342    Visitor *_visitor;
[244]1343    //Pointer to the map of reached status of the nodes.
[100]1344    ReachedMap *_reached;
[244]1345    //Indicates if _reached is locally allocated (true) or not.
[100]1346    bool local_reached;
1347
1348    std::vector<typename Digraph::Node> _list;
1349    int _list_front, _list_back;
1350
[280]1351    //Creates the maps if necessary.
[100]1352    void create_maps() {
1353      if(!_reached) {
[209]1354        local_reached = true;
1355        _reached = Traits::createReachedMap(*_digraph);
[100]1356      }
1357    }
1358
1359  protected:
1360
1361    BfsVisit() {}
[209]1362
[100]1363  public:
1364
1365    typedef BfsVisit Create;
1366
1367    /// \name Named template parameters
1368
1369    ///@{
1370    template <class T>
[257]1371    struct SetReachedMapTraits : public Traits {
[100]1372      typedef T ReachedMap;
1373      static ReachedMap *createReachedMap(const Digraph &digraph) {
[290]1374        LEMON_ASSERT(false, "ReachedMap is not initialized");
1375        return 0; // ignore warnings
[100]1376      }
1377    };
[209]1378    /// \brief \ref named-templ-param "Named parameter" for setting
[244]1379    /// ReachedMap type.
[100]1380    ///
[244]1381    /// \ref named-templ-param "Named parameter" for setting ReachedMap type.
[100]1382    template <class T>
[257]1383    struct SetReachedMap : public BfsVisit< Digraph, Visitor,
1384                                            SetReachedMapTraits<T> > {
1385      typedef BfsVisit< Digraph, Visitor, SetReachedMapTraits<T> > Create;
[100]1386    };
1387    ///@}
1388
[209]1389  public:
1390
[100]1391    /// \brief Constructor.
1392    ///
1393    /// Constructor.
1394    ///
[244]1395    /// \param digraph The digraph the algorithm runs on.
1396    /// \param visitor The visitor object of the algorithm.
[209]1397    BfsVisit(const Digraph& digraph, Visitor& visitor)
[100]1398      : _digraph(&digraph), _visitor(&visitor),
[209]1399        _reached(0), local_reached(false) {}
1400
[100]1401    /// \brief Destructor.
1402    ~BfsVisit() {
1403      if(local_reached) delete _reached;
1404    }
1405
[244]1406    /// \brief Sets the map that indicates which nodes are reached.
[100]1407    ///
[244]1408    /// Sets the map that indicates which nodes are reached.
[100]1409    /// If you don't use this function before calling \ref run(),
[244]1410    /// it will allocate one. The destructor deallocates this
[100]1411    /// automatically allocated map, of course.
1412    /// \return <tt> (*this) </tt>
1413    BfsVisit &reachedMap(ReachedMap &m) {
1414      if(local_reached) {
[209]1415        delete _reached;
1416        local_reached = false;
[100]1417      }
1418      _reached = &m;
1419      return *this;
1420    }
1421
1422  public:
[244]1423
[100]1424    /// \name Execution control
1425    /// The simplest way to execute the algorithm is to use
[244]1426    /// one of the member functions called \ref lemon::BfsVisit::run()
1427    /// "run()".
[100]1428    /// \n
[244]1429    /// If you need more control on the execution, first you must call
1430    /// \ref lemon::BfsVisit::init() "init()", then you can add several
1431    /// source nodes with \ref lemon::BfsVisit::addSource() "addSource()".
1432    /// Finally \ref lemon::BfsVisit::start() "start()" will perform the
1433    /// actual path computation.
[100]1434
1435    /// @{
[244]1436
[100]1437    /// \brief Initializes the internal data structures.
1438    ///
1439    /// Initializes the internal data structures.
1440    void init() {
1441      create_maps();
1442      _list.resize(countNodes(*_digraph));
1443      _list_front = _list_back = -1;
1444      for (NodeIt u(*_digraph) ; u != INVALID ; ++u) {
[209]1445        _reached->set(u, false);
[100]1446      }
1447    }
[209]1448
[100]1449    /// \brief Adds a new source node.
1450    ///
1451    /// Adds a new source node to the set of nodes to be processed.
1452    void addSource(Node s) {
1453      if(!(*_reached)[s]) {
[209]1454          _reached->set(s,true);
1455          _visitor->start(s);
1456          _visitor->reach(s);
[100]1457          _list[++_list_back] = s;
[209]1458        }
[100]1459    }
[209]1460
[100]1461    /// \brief Processes the next node.
1462    ///
1463    /// Processes the next node.
1464    ///
1465    /// \return The processed node.
1466    ///
[244]1467    /// \pre The queue must not be empty.
[209]1468    Node processNextNode() {
[100]1469      Node n = _list[++_list_front];
1470      _visitor->process(n);
1471      Arc e;
1472      for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1473        Node m = _digraph->target(e);
1474        if (!(*_reached)[m]) {
1475          _visitor->discover(e);
1476          _visitor->reach(m);
1477          _reached->set(m, true);
1478          _list[++_list_back] = m;
1479        } else {
1480          _visitor->examine(e);
1481        }
1482      }
1483      return n;
1484    }
1485
1486    /// \brief Processes the next node.
1487    ///
[244]1488    /// Processes the next node and checks if the given target node
[100]1489    /// is reached. If the target node is reachable from the processed
[244]1490    /// node, then the \c reach parameter will be set to \c true.
[100]1491    ///
1492    /// \param target The target node.
[244]1493    /// \retval reach Indicates if the target node is reached.
1494    /// It should be initially \c false.
1495    ///
[100]1496    /// \return The processed node.
1497    ///
[244]1498    /// \pre The queue must not be empty.
[100]1499    Node processNextNode(Node target, bool& reach) {
1500      Node n = _list[++_list_front];
1501      _visitor->process(n);
1502      Arc e;
1503      for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1504        Node m = _digraph->target(e);
1505        if (!(*_reached)[m]) {
1506          _visitor->discover(e);
1507          _visitor->reach(m);
1508          _reached->set(m, true);
1509          _list[++_list_back] = m;
1510          reach = reach || (target == m);
1511        } else {
1512          _visitor->examine(e);
1513        }
1514      }
1515      return n;
1516    }
1517
1518    /// \brief Processes the next node.
1519    ///
[244]1520    /// Processes the next node and checks if at least one of reached
1521    /// nodes has \c true value in the \c nm node map. If one node
1522    /// with \c true value is reachable from the processed node, then the
1523    /// \c rnode parameter will be set to the first of such nodes.
[100]1524    ///
[244]1525    /// \param nm A \c bool (or convertible) node map that indicates the
1526    /// possible targets.
[100]1527    /// \retval rnode The reached target node.
[244]1528    /// It should be initially \c INVALID.
1529    ///
[100]1530    /// \return The processed node.
1531    ///
[244]1532    /// \pre The queue must not be empty.
[100]1533    template <typename NM>
1534    Node processNextNode(const NM& nm, Node& rnode) {
1535      Node n = _list[++_list_front];
1536      _visitor->process(n);
1537      Arc e;
1538      for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1539        Node m = _digraph->target(e);
1540        if (!(*_reached)[m]) {
1541          _visitor->discover(e);
1542          _visitor->reach(m);
1543          _reached->set(m, true);
1544          _list[++_list_back] = m;
1545          if (nm[m] && rnode == INVALID) rnode = m;
1546        } else {
1547          _visitor->examine(e);
1548        }
1549      }
1550      return n;
1551    }
1552
[244]1553    /// \brief The next node to be processed.
[100]1554    ///
[244]1555    /// Returns the next node to be processed or \c INVALID if the queue
1556    /// is empty.
1557    Node nextNode() const {
[100]1558      return _list_front != _list_back ? _list[_list_front + 1] : INVALID;
1559    }
1560
1561    /// \brief Returns \c false if there are nodes
[244]1562    /// to be processed.
[100]1563    ///
1564    /// Returns \c false if there are nodes
[244]1565    /// to be processed in the queue.
1566    bool emptyQueue() const { return _list_front == _list_back; }
[100]1567
1568    /// \brief Returns the number of the nodes to be processed.
1569    ///
1570    /// Returns the number of the nodes to be processed in the queue.
[244]1571    int queueSize() const { return _list_back - _list_front; }
[209]1572
[100]1573    /// \brief Executes the algorithm.
1574    ///
1575    /// Executes the algorithm.
1576    ///
[244]1577    /// This method runs the %BFS algorithm from the root node(s)
1578    /// in order to compute the shortest path to each node.
1579    ///
1580    /// The algorithm computes
1581    /// - the shortest path tree (forest),
1582    /// - the distance of each node from the root(s).
1583    ///
1584    /// \pre init() must be called and at least one root node should be added
[100]1585    /// with addSource() before using this function.
[244]1586    ///
1587    /// \note <tt>b.start()</tt> is just a shortcut of the following code.
1588    /// \code
1589    ///   while ( !b.emptyQueue() ) {
1590    ///     b.processNextNode();
1591    ///   }
1592    /// \endcode
[100]1593    void start() {
1594      while ( !emptyQueue() ) processNextNode();
1595    }
[209]1596
[244]1597    /// \brief Executes the algorithm until the given target node is reached.
[100]1598    ///
[244]1599    /// Executes the algorithm until the given target node is reached.
[100]1600    ///
[244]1601    /// This method runs the %BFS algorithm from the root node(s)
[286]1602    /// in order to compute the shortest path to \c t.
[244]1603    ///
1604    /// The algorithm computes
[286]1605    /// - the shortest path to \c t,
1606    /// - the distance of \c t from the root(s).
[244]1607    ///
1608    /// \pre init() must be called and at least one root node should be
1609    /// added with addSource() before using this function.
1610    ///
1611    /// \note <tt>b.start(t)</tt> is just a shortcut of the following code.
1612    /// \code
1613    ///   bool reach = false;
1614    ///   while ( !b.emptyQueue() && !reach ) {
1615    ///     b.processNextNode(t, reach);
1616    ///   }
1617    /// \endcode
[286]1618    void start(Node t) {
[100]1619      bool reach = false;
[286]1620      while ( !emptyQueue() && !reach ) processNextNode(t, reach);
[100]1621    }
[209]1622
[100]1623    /// \brief Executes the algorithm until a condition is met.
1624    ///
1625    /// Executes the algorithm until a condition is met.
1626    ///
[244]1627    /// This method runs the %BFS algorithm from the root node(s) in
1628    /// order to compute the shortest path to a node \c v with
1629    /// <tt>nm[v]</tt> true, if such a node can be found.
[100]1630    ///
[244]1631    /// \param nm must be a bool (or convertible) node map. The
1632    /// algorithm will stop when it reaches a node \c v with
[100]1633    /// <tt>nm[v]</tt> true.
1634    ///
[244]1635    /// \return The reached node \c v with <tt>nm[v]</tt> true or
1636    /// \c INVALID if no such node was found.
1637    ///
1638    /// \pre init() must be called and at least one root node should be
1639    /// added with addSource() before using this function.
1640    ///
1641    /// \note <tt>b.start(nm)</tt> is just a shortcut of the following code.
1642    /// \code
1643    ///   Node rnode = INVALID;
1644    ///   while ( !b.emptyQueue() && rnode == INVALID ) {
1645    ///     b.processNextNode(nm, rnode);
1646    ///   }
1647    ///   return rnode;
1648    /// \endcode
[100]1649    template <typename NM>
1650    Node start(const NM &nm) {
1651      Node rnode = INVALID;
1652      while ( !emptyQueue() && rnode == INVALID ) {
[209]1653        processNextNode(nm, rnode);
[100]1654      }
1655      return rnode;
1656    }
1657
[286]1658    /// \brief Runs the algorithm from the given source node.
[100]1659    ///
[244]1660    /// This method runs the %BFS algorithm from node \c s
1661    /// in order to compute the shortest path to each node.
1662    ///
1663    /// The algorithm computes
1664    /// - the shortest path tree,
1665    /// - the distance of each node from the root.
1666    ///
1667    /// \note <tt>b.run(s)</tt> is just a shortcut of the following code.
[100]1668    ///\code
1669    ///   b.init();
1670    ///   b.addSource(s);
1671    ///   b.start();
1672    ///\endcode
1673    void run(Node s) {
1674      init();
1675      addSource(s);
1676      start();
1677    }
1678
[286]1679    /// \brief Finds the shortest path between \c s and \c t.
1680    ///
1681    /// This method runs the %BFS algorithm from node \c s
1682    /// in order to compute the shortest path to node \c t
1683    /// (it stops searching when \c t is processed).
1684    ///
1685    /// \return \c true if \c t is reachable form \c s.
1686    ///
1687    /// \note Apart from the return value, <tt>b.run(s,t)</tt> is just a
1688    /// shortcut of the following code.
1689    ///\code
1690    ///   b.init();
1691    ///   b.addSource(s);
1692    ///   b.start(t);
1693    ///\endcode
1694    bool run(Node s,Node t) {
1695      init();
1696      addSource(s);
1697      start(t);
1698      return reached(t);
1699    }
1700
[244]1701    /// \brief Runs the algorithm to visit all nodes in the digraph.
[209]1702    ///
[100]1703    /// This method runs the %BFS algorithm in order to
[244]1704    /// compute the shortest path to each node.
[100]1705    ///
[244]1706    /// The algorithm computes
1707    /// - the shortest path tree (forest),
1708    /// - the distance of each node from the root(s).
1709    ///
1710    /// \note <tt>b.run(s)</tt> is just a shortcut of the following code.
[100]1711    ///\code
1712    ///  b.init();
[244]1713    ///  for (NodeIt n(gr); n != INVALID; ++n) {
1714    ///    if (!b.reached(n)) {
1715    ///      b.addSource(n);
[100]1716    ///      b.start();
1717    ///    }
1718    ///  }
1719    ///\endcode
1720    void run() {
1721      init();
1722      for (NodeIt it(*_digraph); it != INVALID; ++it) {
1723        if (!reached(it)) {
1724          addSource(it);
1725          start();
1726        }
1727      }
1728    }
[244]1729
[100]1730    ///@}
1731
1732    /// \name Query Functions
1733    /// The result of the %BFS algorithm can be obtained using these
1734    /// functions.\n
[244]1735    /// Either \ref lemon::BfsVisit::run() "run()" or
1736    /// \ref lemon::BfsVisit::start() "start()" must be called before
1737    /// using them.
[100]1738    ///@{
1739
[244]1740    /// \brief Checks if a node is reachable from the root(s).
[100]1741    ///
1742    /// Returns \c true if \c v is reachable from the root(s).
1743    /// \pre Either \ref run() or \ref start()
1744    /// must be called before using this function.
1745    bool reached(Node v) { return (*_reached)[v]; }
[244]1746
[100]1747    ///@}
[244]1748
[100]1749  };
1750
1751} //END OF NAMESPACE LEMON
1752
1753#endif
Note: See TracBrowser for help on using the repository browser.