COIN-OR::LEMON - Graph Library

source: lemon-0.x/lemon/bfs.h @ 2334:c1e936e6a46b

Last change on this file since 2334:c1e936e6a46b was 2307:558cc308a4bd, checked in by Balazs Dezso, 17 years ago

Some doc fix

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