COIN-OR::LEMON - Graph Library

source: lemon/lemon/bfs.h @ 349:560e4b6d020d

Last change on this file since 349:560e4b6d020d was 341:d900fd1e760f, checked in by Peter Kovacs <kpeter@…>, 16 years ago

Print the failed line numbers in the unifier script (ticket #138)

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