COIN-OR::LEMON - Graph Library

source: lemon-main/lemon/bfs.h @ 305:069f27927ba9

Last change on this file since 305:069f27927ba9 was 292:e7af73f1805e, checked in by Alpar Juttner <alpar@…>, 16 years ago

Merge

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