COIN-OR::LEMON - Graph Library

source: lemon/lemon/bfs.h @ 282:dc9e8d2c0df9

Last change on this file since 282:dc9e8d2c0df9 was 278:931190050520, checked in by Peter Kovacs <kpeter@…>, 16 years ago

Improve the function-type interface of bfs, dfs, and dijkstra (ticket #96)

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