COIN-OR::LEMON - Graph Library

source: lemon/lemon/bfs.h @ 288:47b3a3b67837

Last change on this file since 288:47b3a3b67837 was 288:47b3a3b67837, checked in by Balazs Dezso <deba@…>, 16 years ago

Use proper traits class in visitor based algorithms

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