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>
31 #include <lemon/path.h>
35 ///Default traits class of Bfs class.
37 ///Default traits class of Bfs class.
38 ///\tparam GR Digraph type.
40 struct BfsDefaultTraits
42 ///The type of the digraph the algorithm runs on.
45 ///\brief The type of the map that stores the predecessor
46 ///arcs of the shortest paths.
48 ///The type of the map that stores the predecessor
49 ///arcs of the shortest paths.
50 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
51 typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
52 ///Instantiates a \ref PredMap.
54 ///This function instantiates a \ref PredMap.
55 ///\param g is the digraph, to which we would like to define the
57 ///\todo The digraph alone may be insufficient to initialize
58 static PredMap *createPredMap(const Digraph &g)
60 return new PredMap(g);
63 ///The type of the map that indicates which nodes are processed.
65 ///The type of the map that indicates which nodes are processed.
66 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
67 ///By default it is a NullMap.
68 typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
69 ///Instantiates a \ref ProcessedMap.
71 ///This function instantiates a \ref ProcessedMap.
72 ///\param g is the digraph, to which
73 ///we would like to define the \ref ProcessedMap
75 static ProcessedMap *createProcessedMap(const Digraph &g)
77 static ProcessedMap *createProcessedMap(const Digraph &)
80 return new ProcessedMap();
83 ///The type of the map that indicates which nodes are reached.
85 ///The type of the map that indicates which nodes are reached.
86 ///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
87 typedef typename Digraph::template NodeMap<bool> ReachedMap;
88 ///Instantiates a \ref ReachedMap.
90 ///This function instantiates a \ref ReachedMap.
91 ///\param g is the digraph, to which
92 ///we would like to define the \ref ReachedMap.
93 static ReachedMap *createReachedMap(const Digraph &g)
95 return new ReachedMap(g);
98 ///The type of the map that stores the distances of the nodes.
100 ///The type of the map that stores the distances of the nodes.
101 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
102 typedef typename Digraph::template NodeMap<int> DistMap;
103 ///Instantiates a \ref DistMap.
105 ///This function instantiates a \ref DistMap.
106 ///\param g is the digraph, to which we would like to define the
108 static DistMap *createDistMap(const Digraph &g)
110 return new DistMap(g);
114 ///%BFS algorithm class.
117 ///This class provides an efficient implementation of the %BFS algorithm.
119 ///There is also a \ref bfs() "function-type interface" for the BFS
120 ///algorithm, which is convenient in the simplier cases and it can be
123 ///\tparam GR The type of the digraph the algorithm runs on.
124 ///The default value is \ref ListDigraph. The value of GR is not used
125 ///directly by \ref Bfs, it is only passed to \ref BfsDefaultTraits.
126 ///\tparam TR Traits class to set various data types used by the algorithm.
127 ///The default traits class is
128 ///\ref BfsDefaultTraits "BfsDefaultTraits<GR>".
129 ///See \ref BfsDefaultTraits for the documentation of
130 ///a Bfs traits class.
132 template <typename GR,
135 template <typename GR=ListDigraph,
136 typename TR=BfsDefaultTraits<GR> >
140 ///\ref Exception for uninitialized parameters.
142 ///This error represents problems in the initialization of the
143 ///parameters of the algorithm.
144 class UninitializedParameter : public lemon::UninitializedParameter {
146 virtual const char* what() const throw() {
147 return "lemon::Bfs::UninitializedParameter";
151 ///The type of the digraph the algorithm runs on.
152 typedef typename TR::Digraph Digraph;
154 ///\brief The type of the map that stores the predecessor arcs of the
156 typedef typename TR::PredMap PredMap;
157 ///The type of the map that stores the distances of the nodes.
158 typedef typename TR::DistMap DistMap;
159 ///The type of the map that indicates which nodes are reached.
160 typedef typename TR::ReachedMap ReachedMap;
161 ///The type of the map that indicates which nodes are processed.
162 typedef typename TR::ProcessedMap ProcessedMap;
163 ///The type of the paths.
164 typedef PredMapPath<Digraph, PredMap> Path;
171 typedef typename Digraph::Node Node;
172 typedef typename Digraph::NodeIt NodeIt;
173 typedef typename Digraph::Arc Arc;
174 typedef typename Digraph::OutArcIt OutArcIt;
176 //Pointer to the underlying digraph.
178 //Pointer to the map of predecessor arcs.
180 //Indicates if _pred is locally allocated (true) or not.
182 //Pointer to the map of distances.
184 //Indicates if _dist is locally allocated (true) or not.
186 //Pointer to the map of reached status of the nodes.
187 ReachedMap *_reached;
188 //Indicates if _reached is locally allocated (true) or not.
190 //Pointer to the map of processed status of the nodes.
191 ProcessedMap *_processed;
192 //Indicates if _processed is locally allocated (true) or not.
193 bool local_processed;
195 std::vector<typename Digraph::Node> _queue;
196 int _queue_head,_queue_tail,_queue_next_dist;
199 ///Creates the maps if necessary.
200 ///\todo Better memory allocation (instead of new).
205 _pred = Traits::createPredMap(*G);
209 _dist = Traits::createDistMap(*G);
212 local_reached = true;
213 _reached = Traits::createReachedMap(*G);
216 local_processed = true;
217 _processed = Traits::createProcessedMap(*G);
229 ///\name Named template parameters
234 struct SetPredMapTraits : public Traits {
236 static PredMap *createPredMap(const Digraph &)
238 throw UninitializedParameter();
241 ///\brief \ref named-templ-param "Named parameter" for setting
242 ///\ref PredMap type.
244 ///\ref named-templ-param "Named parameter" for setting
245 ///\ref PredMap type.
247 struct SetPredMap : public Bfs< Digraph, SetPredMapTraits<T> > {
248 typedef Bfs< Digraph, SetPredMapTraits<T> > Create;
252 struct SetDistMapTraits : public Traits {
254 static DistMap *createDistMap(const Digraph &)
256 throw UninitializedParameter();
259 ///\brief \ref named-templ-param "Named parameter" for setting
260 ///\ref DistMap type.
262 ///\ref named-templ-param "Named parameter" for setting
263 ///\ref DistMap type.
265 struct SetDistMap : public Bfs< Digraph, SetDistMapTraits<T> > {
266 typedef Bfs< Digraph, SetDistMapTraits<T> > Create;
270 struct SetReachedMapTraits : public Traits {
271 typedef T ReachedMap;
272 static ReachedMap *createReachedMap(const Digraph &)
274 throw UninitializedParameter();
277 ///\brief \ref named-templ-param "Named parameter" for setting
278 ///\ref ReachedMap type.
280 ///\ref named-templ-param "Named parameter" for setting
281 ///\ref ReachedMap type.
283 struct SetReachedMap : public Bfs< Digraph, SetReachedMapTraits<T> > {
284 typedef Bfs< Digraph, SetReachedMapTraits<T> > Create;
288 struct SetProcessedMapTraits : public Traits {
289 typedef T ProcessedMap;
290 static ProcessedMap *createProcessedMap(const Digraph &)
292 throw UninitializedParameter();
295 ///\brief \ref named-templ-param "Named parameter" for setting
296 ///\ref ProcessedMap type.
298 ///\ref named-templ-param "Named parameter" for setting
299 ///\ref ProcessedMap type.
301 struct SetProcessedMap : public Bfs< Digraph, SetProcessedMapTraits<T> > {
302 typedef Bfs< Digraph, SetProcessedMapTraits<T> > Create;
305 struct SetStandardProcessedMapTraits : public Traits {
306 typedef typename Digraph::template NodeMap<bool> ProcessedMap;
307 static ProcessedMap *createProcessedMap(const Digraph &g)
309 return new ProcessedMap(g);
312 ///\brief \ref named-templ-param "Named parameter" for setting
313 ///\ref ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
315 ///\ref named-templ-param "Named parameter" for setting
316 ///\ref ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
317 ///If you don't set it explicitly, it will be automatically allocated.
318 struct SetStandardProcessedMap :
319 public Bfs< Digraph, SetStandardProcessedMapTraits > {
320 typedef Bfs< Digraph, SetStandardProcessedMapTraits > 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 typename Digraph::template NodeMap<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
852 static PredMap *createPredMap(const Digraph &g)
854 return new PredMap(g);
857 ///The type of the map that indicates which nodes are processed.
859 ///The type of the map that indicates which nodes are processed.
860 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
861 ///By default it is a NullMap.
862 typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
863 ///Instantiates a \ref ProcessedMap.
865 ///This function instantiates a \ref ProcessedMap.
866 ///\param g is the digraph, to which
867 ///we would like to define the \ref ProcessedMap.
869 static ProcessedMap *createProcessedMap(const Digraph &g)
871 static ProcessedMap *createProcessedMap(const Digraph &)
874 return new ProcessedMap();
877 ///The type of the map that indicates which nodes are reached.
879 ///The type of the map that indicates which nodes are reached.
880 ///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
881 typedef typename Digraph::template NodeMap<bool> ReachedMap;
882 ///Instantiates a \ref ReachedMap.
884 ///This function instantiates a \ref ReachedMap.
885 ///\param g is the digraph, to which
886 ///we would like to define the \ref ReachedMap.
887 static ReachedMap *createReachedMap(const Digraph &g)
889 return new ReachedMap(g);
892 ///The type of the map that stores the distances of the nodes.
894 ///The type of the map that stores the distances of the nodes.
895 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
896 typedef typename Digraph::template NodeMap<int> DistMap;
897 ///Instantiates a \ref DistMap.
899 ///This function instantiates a \ref DistMap.
900 ///\param g is the digraph, to which we would like to define
902 static DistMap *createDistMap(const Digraph &g)
904 return new DistMap(g);
907 ///The type of the shortest paths.
909 ///The type of the shortest paths.
910 ///It must meet the \ref concepts::Path "Path" concept.
911 typedef lemon::Path<Digraph> Path;
914 /// Default traits class used by \ref BfsWizard
916 /// To make it easier to use Bfs algorithm
917 /// we have created a wizard class.
918 /// This \ref BfsWizard class needs default traits,
919 /// as well as the \ref Bfs class.
920 /// The \ref BfsWizardBase is a class to be the default traits of the
921 /// \ref BfsWizard class.
923 class BfsWizardBase : public BfsWizardDefaultTraits<GR>
926 typedef BfsWizardDefaultTraits<GR> Base;
928 //The type of the nodes in the digraph.
929 typedef typename Base::Digraph::Node Node;
931 //Pointer to the digraph the algorithm runs on.
933 //Pointer to the map of reached nodes.
935 //Pointer to the map of processed nodes.
937 //Pointer to the map of predecessors arcs.
939 //Pointer to the map of distances.
941 //Pointer to the shortest path to the target node.
943 //Pointer to the distance of the target node.
949 /// This constructor does not require parameters, therefore it initiates
950 /// all of the attributes to \c 0.
951 BfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0),
952 _dist(0), _path(0), _di(0) {}
956 /// This constructor requires one parameter,
957 /// others are initiated to \c 0.
958 /// \param g The digraph the algorithm runs on.
959 BfsWizardBase(const GR &g) :
960 _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
961 _reached(0), _processed(0), _pred(0), _dist(0), _path(0), _di(0) {}
965 /// Auxiliary class for the function-type interface of BFS algorithm.
967 /// This auxiliary class is created to implement the
968 /// \ref bfs() "function-type interface" of \ref Bfs algorithm.
969 /// It does not have own \ref run() method, it uses the functions
970 /// and features of the plain \ref Bfs.
972 /// This class should only be used through the \ref bfs() function,
973 /// which makes it easier to use the algorithm.
975 class BfsWizard : public TR
979 ///The type of the digraph the algorithm runs on.
980 typedef typename TR::Digraph Digraph;
982 typedef typename Digraph::Node Node;
983 typedef typename Digraph::NodeIt NodeIt;
984 typedef typename Digraph::Arc Arc;
985 typedef typename Digraph::OutArcIt OutArcIt;
987 ///\brief The type of the map that stores the predecessor
988 ///arcs of the shortest paths.
989 typedef typename TR::PredMap PredMap;
990 ///\brief The type of the map that stores the distances of the nodes.
991 typedef typename TR::DistMap DistMap;
992 ///\brief The type of the map that indicates which nodes are reached.
993 typedef typename TR::ReachedMap ReachedMap;
994 ///\brief The type of the map that indicates which nodes are processed.
995 typedef typename TR::ProcessedMap ProcessedMap;
996 ///The type of the shortest paths
997 typedef typename TR::Path Path;
1002 BfsWizard() : TR() {}
1004 /// Constructor that requires parameters.
1006 /// Constructor that requires parameters.
1007 /// These parameters will be the default values for the traits class.
1008 /// \param g The digraph the algorithm runs on.
1009 BfsWizard(const Digraph &g) :
1013 BfsWizard(const TR &b) : TR(b) {}
1017 ///Runs BFS algorithm from the given source node.
1019 ///This method runs BFS algorithm from node \c s
1020 ///in order to compute the shortest path to each node.
1023 Bfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
1025 alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1027 alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1029 alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
1030 if (Base::_processed)
1031 alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1038 ///Finds the shortest path between \c s and \c t.
1040 ///This method runs BFS algorithm from node \c s
1041 ///in order to compute the shortest path to node \c t
1042 ///(it stops searching when \c t is processed).
1044 ///\return \c true if \c t is reachable form \c s.
1045 bool run(Node s, Node t)
1047 if (s==INVALID || t==INVALID) throw UninitializedParameter();
1048 Bfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
1050 alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1052 alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1054 alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
1055 if (Base::_processed)
1056 alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1059 *reinterpret_cast<Path*>(Base::_path) = alg.path(t);
1061 *Base::_di = alg.dist(t);
1062 return alg.reached(t);
1065 ///Runs BFS algorithm to visit all nodes in the digraph.
1067 ///This method runs BFS algorithm in order to compute
1068 ///the shortest path to each node.
1075 struct SetPredMapBase : public Base {
1077 static PredMap *createPredMap(const Digraph &) { return 0; };
1078 SetPredMapBase(const TR &b) : TR(b) {}
1080 ///\brief \ref named-func-param "Named parameter"
1081 ///for setting \ref PredMap object.
1083 ///\ref named-func-param "Named parameter"
1084 ///for setting \ref PredMap object.
1086 BfsWizard<SetPredMapBase<T> > predMap(const T &t)
1088 Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1089 return BfsWizard<SetPredMapBase<T> >(*this);
1093 struct SetReachedMapBase : public Base {
1094 typedef T ReachedMap;
1095 static ReachedMap *createReachedMap(const Digraph &) { return 0; };
1096 SetReachedMapBase(const TR &b) : TR(b) {}
1098 ///\brief \ref named-func-param "Named parameter"
1099 ///for setting \ref ReachedMap object.
1101 /// \ref named-func-param "Named parameter"
1102 ///for setting \ref ReachedMap object.
1104 BfsWizard<SetReachedMapBase<T> > reachedMap(const T &t)
1106 Base::_reached=reinterpret_cast<void*>(const_cast<T*>(&t));
1107 return BfsWizard<SetReachedMapBase<T> >(*this);
1111 struct SetDistMapBase : public Base {
1113 static DistMap *createDistMap(const Digraph &) { return 0; };
1114 SetDistMapBase(const TR &b) : TR(b) {}
1116 ///\brief \ref named-func-param "Named parameter"
1117 ///for setting \ref DistMap object.
1119 /// \ref named-func-param "Named parameter"
1120 ///for setting \ref DistMap object.
1122 BfsWizard<SetDistMapBase<T> > distMap(const T &t)
1124 Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1125 return BfsWizard<SetDistMapBase<T> >(*this);
1129 struct SetProcessedMapBase : public Base {
1130 typedef T ProcessedMap;
1131 static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
1132 SetProcessedMapBase(const TR &b) : TR(b) {}
1134 ///\brief \ref named-func-param "Named parameter"
1135 ///for setting \ref ProcessedMap object.
1137 /// \ref named-func-param "Named parameter"
1138 ///for setting \ref ProcessedMap object.
1140 BfsWizard<SetProcessedMapBase<T> > processedMap(const T &t)
1142 Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1143 return BfsWizard<SetProcessedMapBase<T> >(*this);
1147 struct SetPathBase : public Base {
1149 SetPathBase(const TR &b) : TR(b) {}
1151 ///\brief \ref named-func-param "Named parameter"
1152 ///for getting the shortest path to the target node.
1154 ///\ref named-func-param "Named parameter"
1155 ///for getting the shortest path to the target node.
1157 BfsWizard<SetPathBase<T> > path(const T &t)
1159 Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t));
1160 return BfsWizard<SetPathBase<T> >(*this);
1163 ///\brief \ref named-func-param "Named parameter"
1164 ///for getting the distance of the target node.
1166 ///\ref named-func-param "Named parameter"
1167 ///for getting the distance of the target node.
1168 BfsWizard dist(const int &d)
1170 Base::_di=const_cast<int*>(&d);
1176 ///Function-type interface for BFS algorithm.
1179 ///Function-type interface for BFS algorithm.
1181 ///This function also has several \ref named-func-param "named parameters",
1182 ///they are declared as the members of class \ref BfsWizard.
1183 ///The following examples show how to use these parameters.
1185 /// // Compute shortest path from node s to each node
1186 /// bfs(g).predMap(preds).distMap(dists).run(s);
1188 /// // Compute shortest path from s to t
1189 /// bool reached = bfs(g).path(p).dist(d).run(s,t);
1191 ///\warning Don't forget to put the \ref BfsWizard::run() "run()"
1192 ///to the end of the parameter list.
1196 BfsWizard<BfsWizardBase<GR> >
1197 bfs(const GR &digraph)
1199 return BfsWizard<BfsWizardBase<GR> >(digraph);
1203 /// \brief Visitor class for BFS.
1205 /// This class defines the interface of the BfsVisit events, and
1206 /// it could be the base of a real visitor class.
1207 template <typename _Digraph>
1209 typedef _Digraph Digraph;
1210 typedef typename Digraph::Arc Arc;
1211 typedef typename Digraph::Node Node;
1212 /// \brief Called for the source node(s) of the BFS.
1214 /// This function is called for the source node(s) of the BFS.
1215 void start(const Node& node) {}
1216 /// \brief Called when a node is reached first time.
1218 /// This function is called when a node is reached first time.
1219 void reach(const Node& node) {}
1220 /// \brief Called when a node is processed.
1222 /// This function is called when a node is processed.
1223 void process(const Node& node) {}
1224 /// \brief Called when an arc reaches a new node.
1226 /// This function is called when the BFS finds an arc whose target node
1227 /// is not reached yet.
1228 void discover(const Arc& arc) {}
1229 /// \brief Called when an arc is examined but its target node is
1230 /// already discovered.
1232 /// This function is called when an arc is examined but its target node is
1233 /// already discovered.
1234 void examine(const Arc& arc) {}
1237 template <typename _Digraph>
1239 typedef _Digraph Digraph;
1240 typedef typename Digraph::Arc Arc;
1241 typedef typename Digraph::Node Node;
1242 void start(const Node&) {}
1243 void reach(const Node&) {}
1244 void process(const Node&) {}
1245 void discover(const Arc&) {}
1246 void examine(const Arc&) {}
1248 template <typename _Visitor>
1249 struct Constraints {
1250 void constraints() {
1253 visitor.start(node);
1254 visitor.reach(node);
1255 visitor.process(node);
1256 visitor.discover(arc);
1257 visitor.examine(arc);
1264 /// \brief Default traits class of BfsVisit class.
1266 /// Default traits class of BfsVisit class.
1267 /// \tparam _Digraph The type of the digraph the algorithm runs on.
1268 template<class _Digraph>
1269 struct BfsVisitDefaultTraits {
1271 /// \brief The type of the digraph the algorithm runs on.
1272 typedef _Digraph Digraph;
1274 /// \brief The type of the map that indicates which nodes are reached.
1276 /// The type of the map that indicates which nodes are reached.
1277 /// It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
1278 typedef typename Digraph::template NodeMap<bool> ReachedMap;
1280 /// \brief Instantiates a \ref ReachedMap.
1282 /// This function instantiates a \ref ReachedMap.
1283 /// \param digraph is the digraph, to which
1284 /// we would like to define the \ref ReachedMap.
1285 static ReachedMap *createReachedMap(const Digraph &digraph) {
1286 return new ReachedMap(digraph);
1293 /// \brief %BFS algorithm class with visitor interface.
1295 /// This class provides an efficient implementation of the %BFS algorithm
1296 /// with visitor interface.
1298 /// The %BfsVisit class provides an alternative interface to the Bfs
1299 /// class. It works with callback mechanism, the BfsVisit object calls
1300 /// the member functions of the \c Visitor class on every BFS event.
1302 /// This interface of the BFS algorithm should be used in special cases
1303 /// when extra actions have to be performed in connection with certain
1304 /// events of the BFS algorithm. Otherwise consider to use Bfs or bfs()
1307 /// \tparam _Digraph The type of the digraph the algorithm runs on.
1308 /// The default value is
1309 /// \ref ListDigraph. The value of _Digraph is not used directly by
1310 /// \ref BfsVisit, it is only passed to \ref BfsVisitDefaultTraits.
1311 /// \tparam _Visitor The Visitor type that is used by the algorithm.
1312 /// \ref BfsVisitor "BfsVisitor<_Digraph>" is an empty visitor, which
1313 /// does not observe the BFS events. If you want to observe the BFS
1314 /// events, you should implement your own visitor class.
1315 /// \tparam _Traits Traits class to set various data types used by the
1316 /// algorithm. The default traits class is
1317 /// \ref BfsVisitDefaultTraits "BfsVisitDefaultTraits<_Digraph>".
1318 /// See \ref BfsVisitDefaultTraits for the documentation of
1319 /// a BFS visit traits class.
1321 template <typename _Digraph, typename _Visitor, typename _Traits>
1323 template <typename _Digraph = ListDigraph,
1324 typename _Visitor = BfsVisitor<_Digraph>,
1325 typename _Traits = BfsDefaultTraits<_Digraph> >
1330 /// \brief \ref Exception for uninitialized parameters.
1332 /// This error represents problems in the initialization
1333 /// of the parameters of the algorithm.
1334 class UninitializedParameter : public lemon::UninitializedParameter {
1336 virtual const char* what() const throw()
1338 return "lemon::BfsVisit::UninitializedParameter";
1342 ///The traits class.
1343 typedef _Traits Traits;
1345 ///The type of the digraph the algorithm runs on.
1346 typedef typename Traits::Digraph Digraph;
1348 ///The visitor type used by the algorithm.
1349 typedef _Visitor Visitor;
1351 ///The type of the map that indicates which nodes are reached.
1352 typedef typename Traits::ReachedMap ReachedMap;
1356 typedef typename Digraph::Node Node;
1357 typedef typename Digraph::NodeIt NodeIt;
1358 typedef typename Digraph::Arc Arc;
1359 typedef typename Digraph::OutArcIt OutArcIt;
1361 //Pointer to the underlying digraph.
1362 const Digraph *_digraph;
1363 //Pointer to the visitor object.
1365 //Pointer to the map of reached status of the nodes.
1366 ReachedMap *_reached;
1367 //Indicates if _reached is locally allocated (true) or not.
1370 std::vector<typename Digraph::Node> _list;
1371 int _list_front, _list_back;
1373 ///Creates the maps if necessary.
1374 ///\todo Better memory allocation (instead of new).
1375 void create_maps() {
1377 local_reached = true;
1378 _reached = Traits::createReachedMap(*_digraph);
1388 typedef BfsVisit Create;
1390 /// \name Named template parameters
1394 struct SetReachedMapTraits : public Traits {
1395 typedef T ReachedMap;
1396 static ReachedMap *createReachedMap(const Digraph &digraph) {
1397 throw UninitializedParameter();
1400 /// \brief \ref named-templ-param "Named parameter" for setting
1401 /// ReachedMap type.
1403 /// \ref named-templ-param "Named parameter" for setting ReachedMap type.
1405 struct SetReachedMap : public BfsVisit< Digraph, Visitor,
1406 SetReachedMapTraits<T> > {
1407 typedef BfsVisit< Digraph, Visitor, SetReachedMapTraits<T> > Create;
1413 /// \brief Constructor.
1417 /// \param digraph The digraph the algorithm runs on.
1418 /// \param visitor The visitor object of the algorithm.
1419 BfsVisit(const Digraph& digraph, Visitor& visitor)
1420 : _digraph(&digraph), _visitor(&visitor),
1421 _reached(0), local_reached(false) {}
1423 /// \brief Destructor.
1425 if(local_reached) delete _reached;
1428 /// \brief Sets the map that indicates which nodes are reached.
1430 /// Sets the map that indicates which nodes are reached.
1431 /// If you don't use this function before calling \ref run(),
1432 /// it will allocate one. The destructor deallocates this
1433 /// automatically allocated map, of course.
1434 /// \return <tt> (*this) </tt>
1435 BfsVisit &reachedMap(ReachedMap &m) {
1438 local_reached = false;
1446 /// \name Execution control
1447 /// The simplest way to execute the algorithm is to use
1448 /// one of the member functions called \ref lemon::BfsVisit::run()
1451 /// If you need more control on the execution, first you must call
1452 /// \ref lemon::BfsVisit::init() "init()", then you can add several
1453 /// source nodes with \ref lemon::BfsVisit::addSource() "addSource()".
1454 /// Finally \ref lemon::BfsVisit::start() "start()" will perform the
1455 /// actual path computation.
1459 /// \brief Initializes the internal data structures.
1461 /// Initializes the internal data structures.
1464 _list.resize(countNodes(*_digraph));
1465 _list_front = _list_back = -1;
1466 for (NodeIt u(*_digraph) ; u != INVALID ; ++u) {
1467 _reached->set(u, false);
1471 /// \brief Adds a new source node.
1473 /// Adds a new source node to the set of nodes to be processed.
1474 void addSource(Node s) {
1475 if(!(*_reached)[s]) {
1476 _reached->set(s,true);
1479 _list[++_list_back] = s;
1483 /// \brief Processes the next node.
1485 /// Processes the next node.
1487 /// \return The processed node.
1489 /// \pre The queue must not be empty.
1490 Node processNextNode() {
1491 Node n = _list[++_list_front];
1492 _visitor->process(n);
1494 for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1495 Node m = _digraph->target(e);
1496 if (!(*_reached)[m]) {
1497 _visitor->discover(e);
1499 _reached->set(m, true);
1500 _list[++_list_back] = m;
1502 _visitor->examine(e);
1508 /// \brief Processes the next node.
1510 /// Processes the next node and checks if the given target node
1511 /// is reached. If the target node is reachable from the processed
1512 /// node, then the \c reach parameter will be set to \c true.
1514 /// \param target The target node.
1515 /// \retval reach Indicates if the target node is reached.
1516 /// It should be initially \c false.
1518 /// \return The processed node.
1520 /// \pre The queue must not be empty.
1521 Node processNextNode(Node target, bool& reach) {
1522 Node n = _list[++_list_front];
1523 _visitor->process(n);
1525 for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1526 Node m = _digraph->target(e);
1527 if (!(*_reached)[m]) {
1528 _visitor->discover(e);
1530 _reached->set(m, true);
1531 _list[++_list_back] = m;
1532 reach = reach || (target == m);
1534 _visitor->examine(e);
1540 /// \brief Processes the next node.
1542 /// Processes the next node and checks if at least one of reached
1543 /// nodes has \c true value in the \c nm node map. If one node
1544 /// with \c true value is reachable from the processed node, then the
1545 /// \c rnode parameter will be set to the first of such nodes.
1547 /// \param nm A \c bool (or convertible) node map that indicates the
1548 /// possible targets.
1549 /// \retval rnode The reached target node.
1550 /// It should be initially \c INVALID.
1552 /// \return The processed node.
1554 /// \pre The queue must not be empty.
1555 template <typename NM>
1556 Node processNextNode(const NM& nm, Node& rnode) {
1557 Node n = _list[++_list_front];
1558 _visitor->process(n);
1560 for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1561 Node m = _digraph->target(e);
1562 if (!(*_reached)[m]) {
1563 _visitor->discover(e);
1565 _reached->set(m, true);
1566 _list[++_list_back] = m;
1567 if (nm[m] && rnode == INVALID) rnode = m;
1569 _visitor->examine(e);
1575 /// \brief The next node to be processed.
1577 /// Returns the next node to be processed or \c INVALID if the queue
1579 Node nextNode() const {
1580 return _list_front != _list_back ? _list[_list_front + 1] : INVALID;
1583 /// \brief Returns \c false if there are nodes
1584 /// to be processed.
1586 /// Returns \c false if there are nodes
1587 /// to be processed in the queue.
1588 bool emptyQueue() const { return _list_front == _list_back; }
1590 /// \brief Returns the number of the nodes to be processed.
1592 /// Returns the number of the nodes to be processed in the queue.
1593 int queueSize() const { return _list_back - _list_front; }
1595 /// \brief Executes the algorithm.
1597 /// Executes the algorithm.
1599 /// This method runs the %BFS algorithm from the root node(s)
1600 /// in order to compute the shortest path to each node.
1602 /// The algorithm computes
1603 /// - the shortest path tree (forest),
1604 /// - the distance of each node from the root(s).
1606 /// \pre init() must be called and at least one root node should be added
1607 /// with addSource() before using this function.
1609 /// \note <tt>b.start()</tt> is just a shortcut of the following code.
1611 /// while ( !b.emptyQueue() ) {
1612 /// b.processNextNode();
1616 while ( !emptyQueue() ) processNextNode();
1619 /// \brief Executes the algorithm until the given target node is reached.
1621 /// Executes the algorithm until the given target node is reached.
1623 /// This method runs the %BFS algorithm from the root node(s)
1624 /// in order to compute the shortest path to \c dest.
1626 /// The algorithm computes
1627 /// - the shortest path to \c dest,
1628 /// - the distance of \c dest from the root(s).
1630 /// \pre init() must be called and at least one root node should be
1631 /// added with addSource() before using this function.
1633 /// \note <tt>b.start(t)</tt> is just a shortcut of the following code.
1635 /// bool reach = false;
1636 /// while ( !b.emptyQueue() && !reach ) {
1637 /// b.processNextNode(t, reach);
1640 void start(Node dest) {
1642 while ( !emptyQueue() && !reach ) processNextNode(dest, reach);
1645 /// \brief Executes the algorithm until a condition is met.
1647 /// Executes the algorithm until a condition is met.
1649 /// This method runs the %BFS algorithm from the root node(s) in
1650 /// order to compute the shortest path to a node \c v with
1651 /// <tt>nm[v]</tt> true, if such a node can be found.
1653 /// \param nm must be a bool (or convertible) node map. The
1654 /// algorithm will stop when it reaches a node \c v with
1655 /// <tt>nm[v]</tt> true.
1657 /// \return The reached node \c v with <tt>nm[v]</tt> true or
1658 /// \c INVALID if no such node was found.
1660 /// \pre init() must be called and at least one root node should be
1661 /// added with addSource() before using this function.
1663 /// \note <tt>b.start(nm)</tt> is just a shortcut of the following code.
1665 /// Node rnode = INVALID;
1666 /// while ( !b.emptyQueue() && rnode == INVALID ) {
1667 /// b.processNextNode(nm, rnode);
1671 template <typename NM>
1672 Node start(const NM &nm) {
1673 Node rnode = INVALID;
1674 while ( !emptyQueue() && rnode == INVALID ) {
1675 processNextNode(nm, rnode);
1680 /// \brief Runs the algorithm from the given node.
1682 /// This method runs the %BFS algorithm from node \c s
1683 /// in order to compute the shortest path to each node.
1685 /// The algorithm computes
1686 /// - the shortest path tree,
1687 /// - the distance of each node from the root.
1689 /// \note <tt>b.run(s)</tt> is just a shortcut of the following code.
1701 /// \brief Runs the algorithm to visit all nodes in the digraph.
1703 /// This method runs the %BFS algorithm in order to
1704 /// compute the shortest path to each node.
1706 /// The algorithm computes
1707 /// - the shortest path tree (forest),
1708 /// - the distance of each node from the root(s).
1710 /// \note <tt>b.run(s)</tt> is just a shortcut of the following code.
1713 /// for (NodeIt n(gr); n != INVALID; ++n) {
1714 /// if (!b.reached(n)) {
1722 for (NodeIt it(*_digraph); it != INVALID; ++it) {
1732 /// \name Query Functions
1733 /// The result of the %BFS algorithm can be obtained using these
1735 /// Either \ref lemon::BfsVisit::run() "run()" or
1736 /// \ref lemon::BfsVisit::start() "start()" must be called before
1740 /// \brief Checks if a node is reachable from the root(s).
1742 /// Returns \c true if \c v is reachable from the root(s).
1743 /// \pre Either \ref run() or \ref start()
1744 /// must be called before using this function.
1745 bool reached(Node v) { return (*_reached)[v]; }
1751 } //END OF NAMESPACE LEMON