1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
3 * This file is a part of LEMON, a generic C++ optimization library.
5 * Copyright (C) 2003-2008
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
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.
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
24 ///\brief BFS algorithm.
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>
34 ///Default traits class of Bfs class.
36 ///Default traits class of Bfs class.
37 ///\tparam GR Digraph type.
39 struct BfsDefaultTraits
41 ///The type of the digraph the algorithm runs on.
44 ///\brief The type of the map that stores the predecessor
45 ///arcs of the shortest paths.
47 ///The type of the map that stores the predecessor
48 ///arcs of the shortest paths.
49 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
50 typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
51 ///Instantiates a \ref PredMap.
53 ///This function instantiates a \ref PredMap.
54 ///\param g is the digraph, to which we would like to define the
56 ///\todo The digraph alone may be insufficient to initialize
57 static PredMap *createPredMap(const Digraph &g)
59 return new PredMap(g);
62 ///The type of the map that indicates which nodes are processed.
64 ///The type of the map that indicates which nodes are processed.
65 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
66 ///By default it is a NullMap.
67 typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
68 ///Instantiates a \ref ProcessedMap.
70 ///This function instantiates a \ref ProcessedMap.
71 ///\param g is the digraph, to which
72 ///we would like to define the \ref ProcessedMap
74 static ProcessedMap *createProcessedMap(const Digraph &g)
76 static ProcessedMap *createProcessedMap(const Digraph &)
79 return new ProcessedMap();
82 ///The type of the map that indicates which nodes are reached.
84 ///The type of the map that indicates which nodes are reached.
85 ///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
86 typedef typename Digraph::template NodeMap<bool> ReachedMap;
87 ///Instantiates a \ref ReachedMap.
89 ///This function instantiates a \ref ReachedMap.
90 ///\param g is the digraph, to which
91 ///we would like to define the \ref ReachedMap.
92 static ReachedMap *createReachedMap(const Digraph &g)
94 return new ReachedMap(g);
97 ///The type of the map that stores the distances of the nodes.
99 ///The type of the map that stores the distances of the nodes.
100 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
101 typedef typename Digraph::template NodeMap<int> DistMap;
102 ///Instantiates a \ref DistMap.
104 ///This function instantiates a \ref DistMap.
105 ///\param g is the digraph, to which we would like to define the
107 static DistMap *createDistMap(const Digraph &g)
109 return new DistMap(g);
113 ///%BFS algorithm class.
116 ///This class provides an efficient implementation of the %BFS algorithm.
118 ///There is also a \ref bfs() "function type interface" for the BFS
119 ///algorithm, which is convenient in the simplier cases and it can be
122 ///\tparam GR The type of the digraph the algorithm runs on.
123 ///The default value is \ref ListDigraph. The value of GR is not used
124 ///directly by \ref Bfs, it is only passed to \ref BfsDefaultTraits.
125 ///\tparam TR Traits class to set various data types used by the algorithm.
126 ///The default traits class is
127 ///\ref BfsDefaultTraits "BfsDefaultTraits<GR>".
128 ///See \ref BfsDefaultTraits for the documentation of
129 ///a Bfs traits class.
131 template <typename GR,
134 template <typename GR=ListDigraph,
135 typename TR=BfsDefaultTraits<GR> >
139 ///\ref Exception for uninitialized parameters.
141 ///This error represents problems in the initialization of the
142 ///parameters of the algorithm.
143 class UninitializedParameter : public lemon::UninitializedParameter {
145 virtual const char* what() const throw() {
146 return "lemon::Bfs::UninitializedParameter";
150 ///The type of the digraph the algorithm runs on.
151 typedef typename TR::Digraph Digraph;
153 ///\brief The type of the map that stores the predecessor arcs of the
155 typedef typename TR::PredMap PredMap;
156 ///The type of the map that stores the distances of the nodes.
157 typedef typename TR::DistMap DistMap;
158 ///The type of the map that indicates which nodes are reached.
159 typedef typename TR::ReachedMap ReachedMap;
160 ///The type of the map that indicates which nodes are processed.
161 typedef typename TR::ProcessedMap ProcessedMap;
162 ///The type of the paths.
163 typedef PredMapPath<Digraph, PredMap> Path;
170 typedef typename Digraph::Node Node;
171 typedef typename Digraph::NodeIt NodeIt;
172 typedef typename Digraph::Arc Arc;
173 typedef typename Digraph::OutArcIt OutArcIt;
175 //Pointer to the underlying digraph.
177 //Pointer to the map of predecessor arcs.
179 //Indicates if _pred is locally allocated (true) or not.
181 //Pointer to the map of distances.
183 //Indicates if _dist is locally allocated (true) or not.
185 //Pointer to the map of reached status of the nodes.
186 ReachedMap *_reached;
187 //Indicates if _reached is locally allocated (true) or not.
189 //Pointer to the map of processed status of the nodes.
190 ProcessedMap *_processed;
191 //Indicates if _processed is locally allocated (true) or not.
192 bool local_processed;
194 std::vector<typename Digraph::Node> _queue;
195 int _queue_head,_queue_tail,_queue_next_dist;
198 ///Creates the maps if necessary.
199 ///\todo Better memory allocation (instead of new).
204 _pred = Traits::createPredMap(*G);
208 _dist = Traits::createDistMap(*G);
211 local_reached = true;
212 _reached = Traits::createReachedMap(*G);
215 local_processed = true;
216 _processed = Traits::createProcessedMap(*G);
228 ///\name Named template parameters
233 struct DefPredMapTraits : public Traits {
235 static PredMap *createPredMap(const Digraph &)
237 throw UninitializedParameter();
240 ///\brief \ref named-templ-param "Named parameter" for setting
241 ///\ref PredMap type.
243 ///\ref named-templ-param "Named parameter" for setting
244 ///\ref PredMap type.
246 struct DefPredMap : public Bfs< Digraph, DefPredMapTraits<T> > {
247 typedef Bfs< Digraph, DefPredMapTraits<T> > Create;
251 struct DefDistMapTraits : public Traits {
253 static DistMap *createDistMap(const Digraph &)
255 throw UninitializedParameter();
258 ///\brief \ref named-templ-param "Named parameter" for setting
259 ///\ref DistMap type.
261 ///\ref named-templ-param "Named parameter" for setting
262 ///\ref DistMap type.
264 struct DefDistMap : public Bfs< Digraph, DefDistMapTraits<T> > {
265 typedef Bfs< Digraph, DefDistMapTraits<T> > Create;
269 struct DefReachedMapTraits : public Traits {
270 typedef T ReachedMap;
271 static ReachedMap *createReachedMap(const Digraph &)
273 throw UninitializedParameter();
276 ///\brief \ref named-templ-param "Named parameter" for setting
277 ///\ref ReachedMap type.
279 ///\ref named-templ-param "Named parameter" for setting
280 ///\ref ReachedMap type.
282 struct DefReachedMap : public Bfs< Digraph, DefReachedMapTraits<T> > {
283 typedef Bfs< Digraph, DefReachedMapTraits<T> > Create;
287 struct DefProcessedMapTraits : public Traits {
288 typedef T ProcessedMap;
289 static ProcessedMap *createProcessedMap(const Digraph &)
291 throw UninitializedParameter();
294 ///\brief \ref named-templ-param "Named parameter" for setting
295 ///\ref ProcessedMap type.
297 ///\ref named-templ-param "Named parameter" for setting
298 ///\ref ProcessedMap type.
300 struct DefProcessedMap : public Bfs< Digraph, DefProcessedMapTraits<T> > {
301 typedef Bfs< Digraph, DefProcessedMapTraits<T> > Create;
304 struct DefDigraphProcessedMapTraits : public Traits {
305 typedef typename Digraph::template NodeMap<bool> ProcessedMap;
306 static ProcessedMap *createProcessedMap(const Digraph &g)
308 return new ProcessedMap(g);
311 ///\brief \ref named-templ-param "Named parameter" for setting
312 ///\ref ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
314 ///\ref named-templ-param "Named parameter" for setting
315 ///\ref ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
316 ///If you don't set it explicitly, it will be automatically allocated.
318 struct DefProcessedMapToBeDefaultMap :
319 public Bfs< Digraph, DefDigraphProcessedMapTraits> {
320 typedef Bfs< Digraph, DefDigraphProcessedMapTraits> Create;
330 ///\param g The digraph the algorithm runs on.
331 Bfs(const Digraph &g) :
333 _pred(NULL), local_pred(false),
334 _dist(NULL), local_dist(false),
335 _reached(NULL), local_reached(false),
336 _processed(NULL), local_processed(false)
342 if(local_pred) delete _pred;
343 if(local_dist) delete _dist;
344 if(local_reached) delete _reached;
345 if(local_processed) delete _processed;
348 ///Sets the map that stores the predecessor arcs.
350 ///Sets the map that stores the predecessor arcs.
351 ///If you don't use this function before calling \ref run(),
352 ///it will allocate one. The destructor deallocates this
353 ///automatically allocated map, of course.
354 ///\return <tt> (*this) </tt>
355 Bfs &predMap(PredMap &m)
365 ///Sets the map that indicates which nodes are reached.
367 ///Sets the map that indicates which nodes are reached.
368 ///If you don't use this function before calling \ref run(),
369 ///it will allocate one. The destructor deallocates this
370 ///automatically allocated map, of course.
371 ///\return <tt> (*this) </tt>
372 Bfs &reachedMap(ReachedMap &m)
382 ///Sets the map that indicates which nodes are processed.
384 ///Sets the map that indicates which nodes are processed.
385 ///If you don't use this function before calling \ref run(),
386 ///it will allocate one. The destructor deallocates this
387 ///automatically allocated map, of course.
388 ///\return <tt> (*this) </tt>
389 Bfs &processedMap(ProcessedMap &m)
391 if(local_processed) {
393 local_processed=false;
399 ///Sets the map that stores the distances of the nodes.
401 ///Sets the map that stores the distances of the nodes calculated by
403 ///If you don't use this function before calling \ref run(),
404 ///it will allocate one. The destructor deallocates this
405 ///automatically allocated map, of course.
406 ///\return <tt> (*this) </tt>
407 Bfs &distMap(DistMap &m)
419 ///\name Execution control
420 ///The simplest way to execute the algorithm is to use
421 ///one of the member functions called \ref lemon::Bfs::run() "run()".
423 ///If you need more control on the execution, first you must call
424 ///\ref lemon::Bfs::init() "init()", then you can add several source
425 ///nodes with \ref lemon::Bfs::addSource() "addSource()".
426 ///Finally \ref lemon::Bfs::start() "start()" will perform the
427 ///actual path computation.
431 ///Initializes the internal data structures.
433 ///Initializes the internal data structures.
438 _queue.resize(countNodes(*G));
439 _queue_head=_queue_tail=0;
441 for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
442 _pred->set(u,INVALID);
443 _reached->set(u,false);
444 _processed->set(u,false);
448 ///Adds a new source node.
450 ///Adds a new source node to the set of nodes to be processed.
452 void addSource(Node s)
456 _reached->set(s,true);
457 _pred->set(s,INVALID);
459 _queue[_queue_head++]=s;
460 _queue_next_dist=_queue_head;
464 ///Processes the next node.
466 ///Processes the next node.
468 ///\return The processed node.
470 ///\pre The queue must not be empty.
471 Node processNextNode()
473 if(_queue_tail==_queue_next_dist) {
475 _queue_next_dist=_queue_head;
477 Node n=_queue[_queue_tail++];
478 _processed->set(n,true);
480 for(OutArcIt e(*G,n);e!=INVALID;++e)
481 if(!(*_reached)[m=G->target(e)]) {
482 _queue[_queue_head++]=m;
483 _reached->set(m,true);
485 _dist->set(m,_curr_dist);
490 ///Processes the next node.
492 ///Processes the next node and checks if the given target node
493 ///is reached. If the target node is reachable from the processed
494 ///node, then the \c reach parameter will be set to \c true.
496 ///\param target The target node.
497 ///\retval reach Indicates if the target node is reached.
498 ///It should be initially \c false.
500 ///\return The processed node.
502 ///\pre The queue must not be empty.
503 Node processNextNode(Node target, bool& reach)
505 if(_queue_tail==_queue_next_dist) {
507 _queue_next_dist=_queue_head;
509 Node n=_queue[_queue_tail++];
510 _processed->set(n,true);
512 for(OutArcIt e(*G,n);e!=INVALID;++e)
513 if(!(*_reached)[m=G->target(e)]) {
514 _queue[_queue_head++]=m;
515 _reached->set(m,true);
517 _dist->set(m,_curr_dist);
518 reach = reach || (target == m);
523 ///Processes the next node.
525 ///Processes the next node and checks if at least one of reached
526 ///nodes has \c true value in the \c nm node map. If one node
527 ///with \c true value is reachable from the processed node, then the
528 ///\c rnode parameter will be set to the first of such nodes.
530 ///\param nm A \c bool (or convertible) node map that indicates the
532 ///\retval rnode The reached target node.
533 ///It should be initially \c INVALID.
535 ///\return The processed node.
537 ///\pre The queue must not be empty.
539 Node processNextNode(const NM& nm, Node& rnode)
541 if(_queue_tail==_queue_next_dist) {
543 _queue_next_dist=_queue_head;
545 Node n=_queue[_queue_tail++];
546 _processed->set(n,true);
548 for(OutArcIt e(*G,n);e!=INVALID;++e)
549 if(!(*_reached)[m=G->target(e)]) {
550 _queue[_queue_head++]=m;
551 _reached->set(m,true);
553 _dist->set(m,_curr_dist);
554 if (nm[m] && rnode == INVALID) rnode = m;
559 ///The next node to be processed.
561 ///Returns the next node to be processed or \c INVALID if the queue
563 Node nextNode() const
565 return _queue_tail<_queue_head?_queue[_queue_tail]:INVALID;
568 ///\brief Returns \c false if there are nodes
571 ///Returns \c false if there are nodes
572 ///to be processed in the queue.
573 bool emptyQueue() const { return _queue_tail==_queue_head; }
575 ///Returns the number of the nodes to be processed.
577 ///Returns the number of the nodes to be processed in the queue.
578 int queueSize() const { return _queue_head-_queue_tail; }
580 ///Executes the algorithm.
582 ///Executes the algorithm.
584 ///This method runs the %BFS algorithm from the root node(s)
585 ///in order to compute the shortest path to each node.
587 ///The algorithm computes
588 ///- the shortest path tree (forest),
589 ///- the distance of each node from the root(s).
591 ///\pre init() must be called and at least one root node should be
592 ///added with addSource() before using this function.
594 ///\note <tt>b.start()</tt> is just a shortcut of the following code.
596 /// while ( !b.emptyQueue() ) {
597 /// b.processNextNode();
602 while ( !emptyQueue() ) processNextNode();
605 ///Executes the algorithm until the given target node is reached.
607 ///Executes the algorithm until the given target node is reached.
609 ///This method runs the %BFS algorithm from the root node(s)
610 ///in order to compute the shortest path to \c dest.
612 ///The algorithm computes
613 ///- the shortest path to \c dest,
614 ///- the distance of \c dest from the root(s).
616 ///\pre init() must be called and at least one root node should be
617 ///added with addSource() before using this function.
619 ///\note <tt>b.start(t)</tt> is just a shortcut of the following code.
621 /// bool reach = false;
622 /// while ( !b.emptyQueue() && !reach ) {
623 /// b.processNextNode(t, reach);
626 void start(Node dest)
629 while ( !emptyQueue() && !reach ) processNextNode(dest, reach);
632 ///Executes the algorithm until a condition is met.
634 ///Executes the algorithm until a condition is met.
636 ///This method runs the %BFS algorithm from the root node(s) in
637 ///order to compute the shortest path to a node \c v with
638 /// <tt>nm[v]</tt> true, if such a node can be found.
640 ///\param nm A \c bool (or convertible) node map. The algorithm
641 ///will stop when it reaches a node \c v with <tt>nm[v]</tt> true.
643 ///\return The reached node \c v with <tt>nm[v]</tt> true or
644 ///\c INVALID if no such node was found.
646 ///\pre init() must be called and at least one root node should be
647 ///added with addSource() before using this function.
649 ///\note <tt>b.start(nm)</tt> is just a shortcut of the following code.
651 /// Node rnode = INVALID;
652 /// while ( !b.emptyQueue() && rnode == INVALID ) {
653 /// b.processNextNode(nm, rnode);
657 template<class NodeBoolMap>
658 Node start(const NodeBoolMap &nm)
660 Node rnode = INVALID;
661 while ( !emptyQueue() && rnode == INVALID ) {
662 processNextNode(nm, rnode);
667 ///Runs the algorithm from the given node.
669 ///This method runs the %BFS algorithm from node \c s
670 ///in order to compute the shortest path to each node.
672 ///The algorithm computes
673 ///- the shortest path tree,
674 ///- the distance of each node from the root.
676 ///\note <tt>b.run(s)</tt> is just a shortcut of the following code.
688 ///Finds the shortest path between \c s and \c t.
690 ///This method runs the %BFS algorithm from node \c s
691 ///in order to compute the shortest path to \c t.
693 ///\return The length of the shortest <tt>s</tt>--<tt>t</tt> path,
694 ///if \c t is reachable form \c s, \c 0 otherwise.
696 ///\note Apart from the return value, <tt>b.run(s,t)</tt> is just a
697 ///shortcut of the following code.
703 int run(Node s,Node t) {
707 return reached(t) ? _curr_dist : 0;
710 ///Runs the algorithm to visit all nodes in the digraph.
712 ///This method runs the %BFS algorithm in order to
713 ///compute the shortest path to each node.
715 ///The algorithm computes
716 ///- the shortest path tree (forest),
717 ///- the distance of each node from the root(s).
719 ///\note <tt>b.run(s)</tt> is just a shortcut of the following code.
722 /// for (NodeIt n(gr); n != INVALID; ++n) {
723 /// if (!b.reached(n)) {
731 for (NodeIt n(*G); n != INVALID; ++n) {
741 ///\name Query Functions
742 ///The result of the %BFS algorithm can be obtained using these
744 ///Either \ref lemon::Bfs::run() "run()" or \ref lemon::Bfs::start()
745 ///"start()" must be called before using them.
749 ///The shortest path to a node.
751 ///Returns the shortest path to a node.
753 ///\warning \c t should be reachable from the root(s).
755 ///\pre Either \ref run() or \ref start() must be called before
756 ///using this function.
757 Path path(Node t) const { return Path(*G, *_pred, t); }
759 ///The distance of a node from the root(s).
761 ///Returns the distance of a node from the root(s).
763 ///\warning If node \c v is not reachable from the root(s), then
764 ///the return value of this function is undefined.
766 ///\pre Either \ref run() or \ref start() must be called before
767 ///using this function.
768 int dist(Node v) const { return (*_dist)[v]; }
770 ///Returns the 'previous arc' of the shortest path tree for a node.
772 ///This function returns the 'previous arc' of the shortest path
773 ///tree for the node \c v, i.e. it returns the last arc of a
774 ///shortest path from the root(s) to \c v. It is \c INVALID if \c v
775 ///is not reachable from the root(s) or if \c v is a root.
777 ///The shortest path tree used here is equal to the shortest path
778 ///tree used in \ref predNode().
780 ///\pre Either \ref run() or \ref start() must be called before
781 ///using this function.
782 Arc predArc(Node v) const { return (*_pred)[v];}
784 ///Returns the 'previous node' of the shortest path tree for a node.
786 ///This function returns the 'previous node' of the shortest path
787 ///tree for the node \c v, i.e. it returns the last but one node
788 ///from a shortest path from the root(s) to \c v. It is \c INVALID
789 ///if \c v is not reachable from the root(s) or if \c v is a root.
791 ///The shortest path tree used here is equal to the shortest path
792 ///tree used in \ref predArc().
794 ///\pre Either \ref run() or \ref start() must be called before
795 ///using this function.
796 Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
797 G->source((*_pred)[v]); }
799 ///\brief Returns a const reference to the node map that stores the
800 /// distances of the nodes.
802 ///Returns a const reference to the node map that stores the distances
803 ///of the nodes calculated by the algorithm.
805 ///\pre Either \ref run() or \ref init()
806 ///must be called before using this function.
807 const DistMap &distMap() const { return *_dist;}
809 ///\brief Returns a const reference to the node map that stores the
812 ///Returns a const reference to the node map that stores the predecessor
813 ///arcs, which form the shortest path tree.
815 ///\pre Either \ref run() or \ref init()
816 ///must be called before using this function.
817 const PredMap &predMap() const { return *_pred;}
819 ///Checks if a node is reachable from the root(s).
821 ///Returns \c true if \c v is reachable from the root(s).
822 ///\pre Either \ref run() or \ref start()
823 ///must be called before using this function.
824 bool reached(Node v) const { return (*_reached)[v]; }
829 ///Default traits class of bfs() function.
831 ///Default traits class of bfs() function.
832 ///\tparam GR Digraph type.
834 struct BfsWizardDefaultTraits
836 ///The type of the digraph the algorithm runs on.
839 ///\brief The type of the map that stores the predecessor
840 ///arcs of the shortest paths.
842 ///The type of the map that stores the predecessor
843 ///arcs of the shortest paths.
844 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
845 typedef NullMap<typename Digraph::Node,typename Digraph::Arc> PredMap;
846 ///Instantiates a \ref PredMap.
848 ///This function instantiates a \ref PredMap.
849 ///\param g is the digraph, to which we would like to define the
851 ///\todo The digraph alone may be insufficient to initialize
853 static PredMap *createPredMap(const Digraph &g)
855 static PredMap *createPredMap(const Digraph &)
858 return new PredMap();
861 ///The type of the map that indicates which nodes are processed.
863 ///The type of the map that indicates which nodes are processed.
864 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
865 typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
866 ///Instantiates a \ref ProcessedMap.
868 ///This function instantiates a \ref ProcessedMap.
869 ///\param g is the digraph, to which
870 ///we would like to define the \ref ProcessedMap.
872 static ProcessedMap *createProcessedMap(const Digraph &g)
874 static ProcessedMap *createProcessedMap(const Digraph &)
877 return new ProcessedMap();
880 ///The type of the map that indicates which nodes are reached.
882 ///The type of the map that indicates which nodes are reached.
883 ///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
884 typedef typename Digraph::template NodeMap<bool> ReachedMap;
885 ///Instantiates a \ref ReachedMap.
887 ///This function instantiates a \ref ReachedMap.
888 ///\param g is the digraph, to which
889 ///we would like to define the \ref ReachedMap.
890 static ReachedMap *createReachedMap(const Digraph &g)
892 return new ReachedMap(g);
895 ///The type of the map that stores the distances of the nodes.
897 ///The type of the map that stores the distances of the nodes.
898 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
900 typedef NullMap<typename Digraph::Node,int> DistMap;
901 ///Instantiates a \ref DistMap.
903 ///This function instantiates a \ref DistMap.
904 ///\param g is the digraph, to which we would like to define
907 static DistMap *createDistMap(const Digraph &g)
909 static DistMap *createDistMap(const Digraph &)
912 return new DistMap();
916 /// Default traits class used by \ref BfsWizard
918 /// To make it easier to use Bfs algorithm
919 /// we have created a wizard class.
920 /// This \ref BfsWizard class needs default traits,
921 /// as well as the \ref Bfs class.
922 /// The \ref BfsWizardBase is a class to be the default traits of the
923 /// \ref BfsWizard class.
925 class BfsWizardBase : public BfsWizardDefaultTraits<GR>
928 typedef BfsWizardDefaultTraits<GR> Base;
930 //The type of the nodes in the digraph.
931 typedef typename Base::Digraph::Node Node;
933 //Pointer to the digraph the algorithm runs on.
935 //Pointer to the map of reached nodes.
937 //Pointer to the map of processed nodes.
939 //Pointer to the map of predecessors arcs.
941 //Pointer to the map of distances.
943 //Pointer to the source node.
949 /// This constructor does not require parameters, therefore it initiates
950 /// all of the attributes to default values (0, INVALID).
951 BfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0),
952 _dist(0), _source(INVALID) {}
956 /// This constructor requires some parameters,
957 /// listed in the parameters list.
958 /// Others are initiated to 0.
959 /// \param g The digraph the algorithm runs on.
960 /// \param s The source node.
961 BfsWizardBase(const GR &g, Node s=INVALID) :
962 _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
963 _reached(0), _processed(0), _pred(0), _dist(0), _source(s) {}
967 /// Auxiliary class for the function type interface of BFS algorithm.
969 /// This auxiliary class is created to implement the function type
970 /// interface of \ref Bfs algorithm. It uses the functions and features
971 /// of the plain \ref Bfs, but it is much simpler to use it.
972 /// It should only be used through the \ref bfs() function, which makes
973 /// it easier to use the algorithm.
975 /// Simplicity means that the way to change the types defined
976 /// in the traits class is based on functions that returns the new class
977 /// and not on templatable built-in classes.
978 /// When using the plain \ref Bfs
979 /// the new class with the modified type comes from
980 /// the original class by using the ::
981 /// operator. In the case of \ref BfsWizard only
982 /// a function have to be called, and it will
983 /// return the needed class.
985 /// It does not have own \ref run() method. When its \ref run() method
986 /// is called, it initiates a plain \ref Bfs object, and calls the
987 /// \ref Bfs::run() method of it.
989 class BfsWizard : public TR
993 ///The type of the digraph the algorithm runs on.
994 typedef typename TR::Digraph Digraph;
996 typedef typename Digraph::Node Node;
997 typedef typename Digraph::NodeIt NodeIt;
998 typedef typename Digraph::Arc Arc;
999 typedef typename Digraph::OutArcIt OutArcIt;
1001 ///\brief The type of the map that stores the predecessor
1002 ///arcs of the shortest paths.
1003 typedef typename TR::PredMap PredMap;
1004 ///\brief The type of the map that stores the distances of the nodes.
1005 typedef typename TR::DistMap DistMap;
1006 ///\brief The type of the map that indicates which nodes are reached.
1007 typedef typename TR::ReachedMap ReachedMap;
1008 ///\brief The type of the map that indicates which nodes are processed.
1009 typedef typename TR::ProcessedMap ProcessedMap;
1014 BfsWizard() : TR() {}
1016 /// Constructor that requires parameters.
1018 /// Constructor that requires parameters.
1019 /// These parameters will be the default values for the traits class.
1020 BfsWizard(const Digraph &g, Node s=INVALID) :
1024 BfsWizard(const TR &b) : TR(b) {}
1028 ///Runs BFS algorithm from a source node.
1030 ///Runs BFS algorithm from a source node.
1031 ///The node can be given with the \ref source() function.
1034 if(Base::_source==INVALID) throw UninitializedParameter();
1035 Bfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
1037 alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
1038 if(Base::_processed)
1039 alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1041 alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1043 alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1044 alg.run(Base::_source);
1047 ///Runs BFS algorithm from the given node.
1049 ///Runs BFS algorithm from the given node.
1050 ///\param s is the given source.
1057 /// Sets the source node, from which the Bfs algorithm runs.
1059 /// Sets the source node, from which the Bfs algorithm runs.
1060 /// \param s is the source node.
1061 BfsWizard<TR> &source(Node s)
1068 struct DefPredMapBase : public Base {
1070 static PredMap *createPredMap(const Digraph &) { return 0; };
1071 DefPredMapBase(const TR &b) : TR(b) {}
1073 ///\brief \ref named-templ-param "Named parameter"
1074 ///for setting \ref PredMap object.
1076 /// \ref named-templ-param "Named parameter"
1077 ///for setting \ref PredMap object.
1079 BfsWizard<DefPredMapBase<T> > predMap(const T &t)
1081 Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1082 return BfsWizard<DefPredMapBase<T> >(*this);
1086 struct DefReachedMapBase : public Base {
1087 typedef T ReachedMap;
1088 static ReachedMap *createReachedMap(const Digraph &) { return 0; };
1089 DefReachedMapBase(const TR &b) : TR(b) {}
1091 ///\brief \ref named-templ-param "Named parameter"
1092 ///for setting \ref ReachedMap object.
1094 /// \ref named-templ-param "Named parameter"
1095 ///for setting \ref ReachedMap object.
1097 BfsWizard<DefReachedMapBase<T> > reachedMap(const T &t)
1099 Base::_reached=reinterpret_cast<void*>(const_cast<T*>(&t));
1100 return BfsWizard<DefReachedMapBase<T> >(*this);
1104 struct DefProcessedMapBase : public Base {
1105 typedef T ProcessedMap;
1106 static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
1107 DefProcessedMapBase(const TR &b) : TR(b) {}
1109 ///\brief \ref named-templ-param "Named parameter"
1110 ///for setting \ref ProcessedMap object.
1112 /// \ref named-templ-param "Named parameter"
1113 ///for setting \ref ProcessedMap object.
1115 BfsWizard<DefProcessedMapBase<T> > processedMap(const T &t)
1117 Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1118 return BfsWizard<DefProcessedMapBase<T> >(*this);
1122 struct DefDistMapBase : public Base {
1124 static DistMap *createDistMap(const Digraph &) { return 0; };
1125 DefDistMapBase(const TR &b) : TR(b) {}
1127 ///\brief \ref named-templ-param "Named parameter"
1128 ///for setting \ref DistMap object.
1130 /// \ref named-templ-param "Named parameter"
1131 ///for setting \ref DistMap object.
1133 BfsWizard<DefDistMapBase<T> > distMap(const T &t)
1135 Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1136 return BfsWizard<DefDistMapBase<T> >(*this);
1141 ///Function type interface for Bfs algorithm.
1144 ///Function type interface for Bfs algorithm.
1146 ///This function also has several
1147 ///\ref named-templ-func-param "named parameters",
1148 ///they are declared as the members of class \ref BfsWizard.
1150 ///example shows how to use these parameters.
1152 /// bfs(g,source).predMap(preds).run();
1154 ///\warning Don't forget to put the \ref BfsWizard::run() "run()"
1155 ///to the end of the parameter list.
1159 BfsWizard<BfsWizardBase<GR> >
1160 bfs(const GR &g,typename GR::Node s=INVALID)
1162 return BfsWizard<BfsWizardBase<GR> >(g,s);
1166 /// \brief Visitor class for BFS.
1168 /// This class defines the interface of the BfsVisit events, and
1169 /// it could be the base of a real visitor class.
1170 template <typename _Digraph>
1172 typedef _Digraph Digraph;
1173 typedef typename Digraph::Arc Arc;
1174 typedef typename Digraph::Node Node;
1175 /// \brief Called for the source node(s) of the BFS.
1177 /// This function is called for the source node(s) of the BFS.
1178 void start(const Node& node) {}
1179 /// \brief Called when a node is reached first time.
1181 /// This function is called when a node is reached first time.
1182 void reach(const Node& node) {}
1183 /// \brief Called when a node is processed.
1185 /// This function is called when a node is processed.
1186 void process(const Node& node) {}
1187 /// \brief Called when an arc reaches a new node.
1189 /// This function is called when the BFS finds an arc whose target node
1190 /// is not reached yet.
1191 void discover(const Arc& arc) {}
1192 /// \brief Called when an arc is examined but its target node is
1193 /// already discovered.
1195 /// This function is called when an arc is examined but its target node is
1196 /// already discovered.
1197 void examine(const Arc& arc) {}
1200 template <typename _Digraph>
1202 typedef _Digraph Digraph;
1203 typedef typename Digraph::Arc Arc;
1204 typedef typename Digraph::Node Node;
1205 void start(const Node&) {}
1206 void reach(const Node&) {}
1207 void process(const Node&) {}
1208 void discover(const Arc&) {}
1209 void examine(const Arc&) {}
1211 template <typename _Visitor>
1212 struct Constraints {
1213 void constraints() {
1216 visitor.start(node);
1217 visitor.reach(node);
1218 visitor.process(node);
1219 visitor.discover(arc);
1220 visitor.examine(arc);
1227 /// \brief Default traits class of BfsVisit class.
1229 /// Default traits class of BfsVisit class.
1230 /// \tparam _Digraph The type of the digraph the algorithm runs on.
1231 template<class _Digraph>
1232 struct BfsVisitDefaultTraits {
1234 /// \brief The type of the digraph the algorithm runs on.
1235 typedef _Digraph Digraph;
1237 /// \brief The type of the map that indicates which nodes are reached.
1239 /// The type of the map that indicates which nodes are reached.
1240 /// It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
1241 typedef typename Digraph::template NodeMap<bool> ReachedMap;
1243 /// \brief Instantiates a \ref ReachedMap.
1245 /// This function instantiates a \ref ReachedMap.
1246 /// \param digraph is the digraph, to which
1247 /// we would like to define the \ref ReachedMap.
1248 static ReachedMap *createReachedMap(const Digraph &digraph) {
1249 return new ReachedMap(digraph);
1256 /// \brief %BFS algorithm class with visitor interface.
1258 /// This class provides an efficient implementation of the %BFS algorithm
1259 /// with visitor interface.
1261 /// The %BfsVisit class provides an alternative interface to the Bfs
1262 /// class. It works with callback mechanism, the BfsVisit object calls
1263 /// the member functions of the \c Visitor class on every BFS event.
1265 /// This interface of the BFS algorithm should be used in special cases
1266 /// when extra actions have to be performed in connection with certain
1267 /// events of the BFS algorithm. Otherwise consider to use Bfs or bfs()
1270 /// \tparam _Digraph The type of the digraph the algorithm runs on.
1271 /// The default value is
1272 /// \ref ListDigraph. The value of _Digraph is not used directly by
1273 /// \ref BfsVisit, it is only passed to \ref BfsVisitDefaultTraits.
1274 /// \tparam _Visitor The Visitor type that is used by the algorithm.
1275 /// \ref BfsVisitor "BfsVisitor<_Digraph>" is an empty visitor, which
1276 /// does not observe the BFS events. If you want to observe the BFS
1277 /// events, you should implement your own visitor class.
1278 /// \tparam _Traits Traits class to set various data types used by the
1279 /// algorithm. The default traits class is
1280 /// \ref BfsVisitDefaultTraits "BfsVisitDefaultTraits<_Digraph>".
1281 /// See \ref BfsVisitDefaultTraits for the documentation of
1282 /// a BFS visit traits class.
1284 template <typename _Digraph, typename _Visitor, typename _Traits>
1286 template <typename _Digraph = ListDigraph,
1287 typename _Visitor = BfsVisitor<_Digraph>,
1288 typename _Traits = BfsDefaultTraits<_Digraph> >
1293 /// \brief \ref Exception for uninitialized parameters.
1295 /// This error represents problems in the initialization
1296 /// of the parameters of the algorithm.
1297 class UninitializedParameter : public lemon::UninitializedParameter {
1299 virtual const char* what() const throw()
1301 return "lemon::BfsVisit::UninitializedParameter";
1305 ///The traits class.
1306 typedef _Traits Traits;
1308 ///The type of the digraph the algorithm runs on.
1309 typedef typename Traits::Digraph Digraph;
1311 ///The visitor type used by the algorithm.
1312 typedef _Visitor Visitor;
1314 ///The type of the map that indicates which nodes are reached.
1315 typedef typename Traits::ReachedMap ReachedMap;
1319 typedef typename Digraph::Node Node;
1320 typedef typename Digraph::NodeIt NodeIt;
1321 typedef typename Digraph::Arc Arc;
1322 typedef typename Digraph::OutArcIt OutArcIt;
1324 //Pointer to the underlying digraph.
1325 const Digraph *_digraph;
1326 //Pointer to the visitor object.
1328 //Pointer to the map of reached status of the nodes.
1329 ReachedMap *_reached;
1330 //Indicates if _reached is locally allocated (true) or not.
1333 std::vector<typename Digraph::Node> _list;
1334 int _list_front, _list_back;
1336 ///Creates the maps if necessary.
1337 ///\todo Better memory allocation (instead of new).
1338 void create_maps() {
1340 local_reached = true;
1341 _reached = Traits::createReachedMap(*_digraph);
1351 typedef BfsVisit Create;
1353 /// \name Named template parameters
1357 struct DefReachedMapTraits : public Traits {
1358 typedef T ReachedMap;
1359 static ReachedMap *createReachedMap(const Digraph &digraph) {
1360 throw UninitializedParameter();
1363 /// \brief \ref named-templ-param "Named parameter" for setting
1364 /// ReachedMap type.
1366 /// \ref named-templ-param "Named parameter" for setting ReachedMap type.
1368 struct DefReachedMap : public BfsVisit< Digraph, Visitor,
1369 DefReachedMapTraits<T> > {
1370 typedef BfsVisit< Digraph, Visitor, DefReachedMapTraits<T> > Create;
1376 /// \brief Constructor.
1380 /// \param digraph The digraph the algorithm runs on.
1381 /// \param visitor The visitor object of the algorithm.
1382 BfsVisit(const Digraph& digraph, Visitor& visitor)
1383 : _digraph(&digraph), _visitor(&visitor),
1384 _reached(0), local_reached(false) {}
1386 /// \brief Destructor.
1388 if(local_reached) delete _reached;
1391 /// \brief Sets the map that indicates which nodes are reached.
1393 /// Sets the map that indicates which nodes are reached.
1394 /// If you don't use this function before calling \ref run(),
1395 /// it will allocate one. The destructor deallocates this
1396 /// automatically allocated map, of course.
1397 /// \return <tt> (*this) </tt>
1398 BfsVisit &reachedMap(ReachedMap &m) {
1401 local_reached = false;
1409 /// \name Execution control
1410 /// The simplest way to execute the algorithm is to use
1411 /// one of the member functions called \ref lemon::BfsVisit::run()
1414 /// If you need more control on the execution, first you must call
1415 /// \ref lemon::BfsVisit::init() "init()", then you can add several
1416 /// source nodes with \ref lemon::BfsVisit::addSource() "addSource()".
1417 /// Finally \ref lemon::BfsVisit::start() "start()" will perform the
1418 /// actual path computation.
1422 /// \brief Initializes the internal data structures.
1424 /// Initializes the internal data structures.
1427 _list.resize(countNodes(*_digraph));
1428 _list_front = _list_back = -1;
1429 for (NodeIt u(*_digraph) ; u != INVALID ; ++u) {
1430 _reached->set(u, false);
1434 /// \brief Adds a new source node.
1436 /// Adds a new source node to the set of nodes to be processed.
1437 void addSource(Node s) {
1438 if(!(*_reached)[s]) {
1439 _reached->set(s,true);
1442 _list[++_list_back] = s;
1446 /// \brief Processes the next node.
1448 /// Processes the next node.
1450 /// \return The processed node.
1452 /// \pre The queue must not be empty.
1453 Node processNextNode() {
1454 Node n = _list[++_list_front];
1455 _visitor->process(n);
1457 for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1458 Node m = _digraph->target(e);
1459 if (!(*_reached)[m]) {
1460 _visitor->discover(e);
1462 _reached->set(m, true);
1463 _list[++_list_back] = m;
1465 _visitor->examine(e);
1471 /// \brief Processes the next node.
1473 /// Processes the next node and checks if the given target node
1474 /// is reached. If the target node is reachable from the processed
1475 /// node, then the \c reach parameter will be set to \c true.
1477 /// \param target The target node.
1478 /// \retval reach Indicates if the target node is reached.
1479 /// It should be initially \c false.
1481 /// \return The processed node.
1483 /// \pre The queue must not be empty.
1484 Node processNextNode(Node target, bool& reach) {
1485 Node n = _list[++_list_front];
1486 _visitor->process(n);
1488 for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1489 Node m = _digraph->target(e);
1490 if (!(*_reached)[m]) {
1491 _visitor->discover(e);
1493 _reached->set(m, true);
1494 _list[++_list_back] = m;
1495 reach = reach || (target == m);
1497 _visitor->examine(e);
1503 /// \brief Processes the next node.
1505 /// Processes the next node and checks if at least one of reached
1506 /// nodes has \c true value in the \c nm node map. If one node
1507 /// with \c true value is reachable from the processed node, then the
1508 /// \c rnode parameter will be set to the first of such nodes.
1510 /// \param nm A \c bool (or convertible) node map that indicates the
1511 /// possible targets.
1512 /// \retval rnode The reached target node.
1513 /// It should be initially \c INVALID.
1515 /// \return The processed node.
1517 /// \pre The queue must not be empty.
1518 template <typename NM>
1519 Node processNextNode(const NM& nm, Node& rnode) {
1520 Node n = _list[++_list_front];
1521 _visitor->process(n);
1523 for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1524 Node m = _digraph->target(e);
1525 if (!(*_reached)[m]) {
1526 _visitor->discover(e);
1528 _reached->set(m, true);
1529 _list[++_list_back] = m;
1530 if (nm[m] && rnode == INVALID) rnode = m;
1532 _visitor->examine(e);
1538 /// \brief The next node to be processed.
1540 /// Returns the next node to be processed or \c INVALID if the queue
1542 Node nextNode() const {
1543 return _list_front != _list_back ? _list[_list_front + 1] : INVALID;
1546 /// \brief Returns \c false if there are nodes
1547 /// to be processed.
1549 /// Returns \c false if there are nodes
1550 /// to be processed in the queue.
1551 bool emptyQueue() const { return _list_front == _list_back; }
1553 /// \brief Returns the number of the nodes to be processed.
1555 /// Returns the number of the nodes to be processed in the queue.
1556 int queueSize() const { return _list_back - _list_front; }
1558 /// \brief Executes the algorithm.
1560 /// Executes the algorithm.
1562 /// This method runs the %BFS algorithm from the root node(s)
1563 /// in order to compute the shortest path to each node.
1565 /// The algorithm computes
1566 /// - the shortest path tree (forest),
1567 /// - the distance of each node from the root(s).
1569 /// \pre init() must be called and at least one root node should be added
1570 /// with addSource() before using this function.
1572 /// \note <tt>b.start()</tt> is just a shortcut of the following code.
1574 /// while ( !b.emptyQueue() ) {
1575 /// b.processNextNode();
1579 while ( !emptyQueue() ) processNextNode();
1582 /// \brief Executes the algorithm until the given target node is reached.
1584 /// Executes the algorithm until the given target node is reached.
1586 /// This method runs the %BFS algorithm from the root node(s)
1587 /// in order to compute the shortest path to \c dest.
1589 /// The algorithm computes
1590 /// - the shortest path to \c dest,
1591 /// - the distance of \c dest from the root(s).
1593 /// \pre init() must be called and at least one root node should be
1594 /// added with addSource() before using this function.
1596 /// \note <tt>b.start(t)</tt> is just a shortcut of the following code.
1598 /// bool reach = false;
1599 /// while ( !b.emptyQueue() && !reach ) {
1600 /// b.processNextNode(t, reach);
1603 void start(Node dest) {
1605 while ( !emptyQueue() && !reach ) processNextNode(dest, reach);
1608 /// \brief Executes the algorithm until a condition is met.
1610 /// Executes the algorithm until a condition is met.
1612 /// This method runs the %BFS algorithm from the root node(s) in
1613 /// order to compute the shortest path to a node \c v with
1614 /// <tt>nm[v]</tt> true, if such a node can be found.
1616 /// \param nm must be a bool (or convertible) node map. The
1617 /// algorithm will stop when it reaches a node \c v with
1618 /// <tt>nm[v]</tt> true.
1620 /// \return The reached node \c v with <tt>nm[v]</tt> true or
1621 /// \c INVALID if no such node was found.
1623 /// \pre init() must be called and at least one root node should be
1624 /// added with addSource() before using this function.
1626 /// \note <tt>b.start(nm)</tt> is just a shortcut of the following code.
1628 /// Node rnode = INVALID;
1629 /// while ( !b.emptyQueue() && rnode == INVALID ) {
1630 /// b.processNextNode(nm, rnode);
1634 template <typename NM>
1635 Node start(const NM &nm) {
1636 Node rnode = INVALID;
1637 while ( !emptyQueue() && rnode == INVALID ) {
1638 processNextNode(nm, rnode);
1643 /// \brief Runs the algorithm from the given node.
1645 /// This method runs the %BFS algorithm from node \c s
1646 /// in order to compute the shortest path to each node.
1648 /// The algorithm computes
1649 /// - the shortest path tree,
1650 /// - the distance of each node from the root.
1652 /// \note <tt>b.run(s)</tt> is just a shortcut of the following code.
1664 /// \brief Runs the algorithm to visit all nodes in the digraph.
1666 /// This method runs the %BFS algorithm in order to
1667 /// compute the shortest path to each node.
1669 /// The algorithm computes
1670 /// - the shortest path tree (forest),
1671 /// - the distance of each node from the root(s).
1673 /// \note <tt>b.run(s)</tt> is just a shortcut of the following code.
1676 /// for (NodeIt n(gr); n != INVALID; ++n) {
1677 /// if (!b.reached(n)) {
1685 for (NodeIt it(*_digraph); it != INVALID; ++it) {
1695 /// \name Query Functions
1696 /// The result of the %BFS algorithm can be obtained using these
1698 /// Either \ref lemon::BfsVisit::run() "run()" or
1699 /// \ref lemon::BfsVisit::start() "start()" must be called before
1703 /// \brief Checks if a node is reachable from the root(s).
1705 /// Returns \c true if \c v is reachable from the root(s).
1706 /// \pre Either \ref run() or \ref start()
1707 /// must be called before using this function.
1708 bool reached(Node v) { return (*_reached)[v]; }
1714 } //END OF NAMESPACE LEMON