3 * This file is a part of LEMON, a generic C++ optimization library
5 * Copyright (C) 2003-2006
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/graph_utils.h>
28 #include <lemon/bits/invalid.h>
29 #include <lemon/error.h>
30 #include <lemon/maps.h>
36 ///Default traits class of Bfs class.
38 ///Default traits class of Bfs class.
39 ///\param GR Graph type.
41 struct BfsDefaultTraits
43 ///The graph type the algorithm runs on.
45 ///\brief The type of the map that stores the last
46 ///edges of the shortest paths.
48 ///The type of the map that stores the last
49 ///edges of the shortest paths.
50 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
52 typedef typename Graph::template NodeMap<typename GR::Edge> PredMap;
53 ///Instantiates a PredMap.
55 ///This function instantiates a \ref PredMap.
56 ///\param G is the graph, to which we would like to define the PredMap.
57 ///\todo The graph alone may be insufficient to initialize
58 static PredMap *createPredMap(const GR &G)
60 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 ///\todo named parameter to set this type, function to read and write.
67 typedef NullMap<typename Graph::Node,bool> ProcessedMap;
68 ///Instantiates a ProcessedMap.
70 ///This function instantiates a \ref ProcessedMap.
71 ///\param g is the graph, to which
72 ///we would like to define the \ref ProcessedMap
74 static ProcessedMap *createProcessedMap(const GR &g)
76 static ProcessedMap *createProcessedMap(const GR &)
79 return new ProcessedMap();
81 ///The type of the map that indicates which nodes are reached.
83 ///The type of the map that indicates which nodes are reached.
84 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
85 ///\todo named parameter to set this type, function to read and write.
86 typedef typename Graph::template NodeMap<bool> ReachedMap;
87 ///Instantiates a ReachedMap.
89 ///This function instantiates a \ref ReachedMap.
90 ///\param G is the graph, to which
91 ///we would like to define the \ref ReachedMap.
92 static ReachedMap *createReachedMap(const GR &G)
94 return new ReachedMap(G);
96 ///The type of the map that stores the dists of the nodes.
98 ///The type of the map that stores the dists of the nodes.
99 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
101 typedef typename Graph::template NodeMap<int> DistMap;
102 ///Instantiates a DistMap.
104 ///This function instantiates a \ref DistMap.
105 ///\param G is the graph, to which we would like to define the \ref DistMap
106 static DistMap *createDistMap(const GR &G)
108 return new DistMap(G);
112 ///%BFS algorithm class.
115 ///This class provides an efficient implementation of the %BFS algorithm.
117 ///\param GR The graph type the algorithm runs on. The default value is
118 ///\ref ListGraph. The value of GR is not used directly by Bfs, it
119 ///is only passed to \ref BfsDefaultTraits.
120 ///\param TR Traits class to set various data types used by the algorithm.
121 ///The default traits class is
122 ///\ref BfsDefaultTraits "BfsDefaultTraits<GR>".
123 ///See \ref BfsDefaultTraits for the documentation of
124 ///a Bfs traits class.
126 ///\author Alpar Juttner
129 template <typename GR,
132 template <typename GR=ListGraph,
133 typename TR=BfsDefaultTraits<GR> >
138 * \brief \ref Exception for uninitialized parameters.
140 * This error represents problems in the initialization
141 * of the parameters of the algorithms.
143 class UninitializedParameter : public lemon::UninitializedParameter {
145 virtual const char* what() const throw() {
146 return "lemon::Bfs::UninitializedParameter";
151 ///The type of the underlying graph.
152 typedef typename TR::Graph Graph;
154 typedef typename Graph::Node Node;
156 typedef typename Graph::NodeIt NodeIt;
158 typedef typename Graph::Edge Edge;
160 typedef typename Graph::OutEdgeIt OutEdgeIt;
162 ///\brief The type of the map that stores the last
163 ///edges of the shortest paths.
164 typedef typename TR::PredMap PredMap;
165 ///The type of the map indicating which nodes are reached.
166 typedef typename TR::ReachedMap ReachedMap;
167 ///The type of the map indicating which nodes are processed.
168 typedef typename TR::ProcessedMap ProcessedMap;
169 ///The type of the map that stores the dists of the nodes.
170 typedef typename TR::DistMap DistMap;
172 /// Pointer to the underlying graph.
174 ///Pointer to the map of predecessors edges.
176 ///Indicates if \ref _pred is locally allocated (\c true) or not.
178 ///Pointer to the map of distances.
180 ///Indicates if \ref _dist is locally allocated (\c true) or not.
182 ///Pointer to the map of reached status of the nodes.
183 ReachedMap *_reached;
184 ///Indicates if \ref _reached is locally allocated (\c true) or not.
186 ///Pointer to the map of processed status of the nodes.
187 ProcessedMap *_processed;
188 ///Indicates if \ref _processed is locally allocated (\c true) or not.
189 bool local_processed;
191 std::vector<typename Graph::Node> _queue;
192 int _queue_head,_queue_tail,_queue_next_dist;
195 ///Creates the maps if necessary.
197 ///\todo Better memory allocation (instead of new).
202 _pred = Traits::createPredMap(*G);
206 _dist = Traits::createDistMap(*G);
209 local_reached = true;
210 _reached = Traits::createReachedMap(*G);
213 local_processed = true;
214 _processed = Traits::createProcessedMap(*G);
226 ///\name Named template parameters
231 struct DefPredMapTraits : public Traits {
233 static PredMap *createPredMap(const Graph &)
235 throw UninitializedParameter();
238 ///\ref named-templ-param "Named parameter" for setting PredMap type
240 ///\ref named-templ-param "Named parameter" for setting PredMap type
243 struct DefPredMap : public Bfs< Graph, DefPredMapTraits<T> > {
244 typedef Bfs< Graph, DefPredMapTraits<T> > Create;
248 struct DefDistMapTraits : public Traits {
250 static DistMap *createDistMap(const Graph &)
252 throw UninitializedParameter();
255 ///\ref named-templ-param "Named parameter" for setting DistMap type
257 ///\ref named-templ-param "Named parameter" for setting DistMap type
260 struct DefDistMap : public Bfs< Graph, DefDistMapTraits<T> > {
261 typedef Bfs< Graph, DefDistMapTraits<T> > Create;
265 struct DefReachedMapTraits : public Traits {
266 typedef T ReachedMap;
267 static ReachedMap *createReachedMap(const Graph &)
269 throw UninitializedParameter();
272 ///\ref named-templ-param "Named parameter" for setting ReachedMap type
274 ///\ref named-templ-param "Named parameter" for setting ReachedMap type
277 struct DefReachedMap : public Bfs< Graph, DefReachedMapTraits<T> > {
278 typedef Bfs< Graph, DefReachedMapTraits<T> > Create;
282 struct DefProcessedMapTraits : public Traits {
283 typedef T ProcessedMap;
284 static ProcessedMap *createProcessedMap(const Graph &)
286 throw UninitializedParameter();
289 ///\ref named-templ-param "Named parameter" for setting ProcessedMap type
291 ///\ref named-templ-param "Named parameter" for setting ProcessedMap type
294 struct DefProcessedMap : public Bfs< Graph, DefProcessedMapTraits<T> > {
295 typedef Bfs< Graph, DefProcessedMapTraits<T> > Create;
298 struct DefGraphProcessedMapTraits : public Traits {
299 typedef typename Graph::template NodeMap<bool> ProcessedMap;
300 static ProcessedMap *createProcessedMap(const Graph &G)
302 return new ProcessedMap(G);
305 ///\brief \ref named-templ-param "Named parameter"
306 ///for setting the ProcessedMap type to be Graph::NodeMap<bool>.
308 ///\ref named-templ-param "Named parameter"
309 ///for setting the ProcessedMap type to be Graph::NodeMap<bool>.
310 ///If you don't set it explicitly, it will be automatically allocated.
312 struct DefProcessedMapToBeDefaultMap :
313 public Bfs< Graph, DefGraphProcessedMapTraits> {
314 typedef Bfs< Graph, DefGraphProcessedMapTraits> Create;
323 ///\param _G the graph the algorithm will run on.
325 Bfs(const Graph& _G) :
327 _pred(NULL), local_pred(false),
328 _dist(NULL), local_dist(false),
329 _reached(NULL), local_reached(false),
330 _processed(NULL), local_processed(false)
336 if(local_pred) delete _pred;
337 if(local_dist) delete _dist;
338 if(local_reached) delete _reached;
339 if(local_processed) delete _processed;
342 ///Sets the map storing the predecessor edges.
344 ///Sets the map storing the predecessor edges.
345 ///If you don't use this function before calling \ref run(),
346 ///it will allocate one. The destructor deallocates this
347 ///automatically allocated map, of course.
348 ///\return <tt> (*this) </tt>
349 Bfs &predMap(PredMap &m)
359 ///Sets the map indicating the reached nodes.
361 ///Sets the map indicating the reached nodes.
362 ///If you don't use this function before calling \ref run(),
363 ///it will allocate one. The destructor deallocates this
364 ///automatically allocated map, of course.
365 ///\return <tt> (*this) </tt>
366 Bfs &reachedMap(ReachedMap &m)
376 ///Sets the map indicating the processed nodes.
378 ///Sets the map indicating the processed nodes.
379 ///If you don't use this function before calling \ref run(),
380 ///it will allocate one. The destructor deallocates this
381 ///automatically allocated map, of course.
382 ///\return <tt> (*this) </tt>
383 Bfs &processedMap(ProcessedMap &m)
385 if(local_processed) {
387 local_processed=false;
393 ///Sets the map storing the distances calculated by the algorithm.
395 ///Sets the map storing the distances calculated by the algorithm.
396 ///If you don't use this function before calling \ref run(),
397 ///it will allocate one. The destructor deallocates this
398 ///automatically allocated map, of course.
399 ///\return <tt> (*this) </tt>
400 Bfs &distMap(DistMap &m)
411 ///\name Execution control
412 ///The simplest way to execute the algorithm is to use
413 ///one of the member functions called \c run(...).
415 ///If you need more control on the execution,
416 ///first you must call \ref init(), then you can add several source nodes
417 ///with \ref addSource().
418 ///Finally \ref start() will perform the actual path
423 ///Initializes the internal data structures.
425 ///Initializes the internal data structures.
430 _queue.resize(countNodes(*G));
431 _queue_head=_queue_tail=0;
433 for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
434 _pred->set(u,INVALID);
435 _reached->set(u,false);
436 _processed->set(u,false);
440 ///Adds a new source node.
442 ///Adds a new source node to the set of nodes to be processed.
444 void addSource(Node s)
448 _reached->set(s,true);
449 _pred->set(s,INVALID);
451 _queue[_queue_head++]=s;
452 _queue_next_dist=_queue_head;
456 ///Processes the next node.
458 ///Processes the next node.
460 ///\return The processed node.
462 ///\warning The queue must not be empty!
463 Node processNextNode()
465 if(_queue_tail==_queue_next_dist) {
467 _queue_next_dist=_queue_head;
469 Node n=_queue[_queue_tail++];
470 _processed->set(n,true);
472 for(OutEdgeIt e(*G,n);e!=INVALID;++e)
473 if(!(*_reached)[m=G->target(e)]) {
474 _queue[_queue_head++]=m;
475 _reached->set(m,true);
477 _dist->set(m,_curr_dist);
482 ///Processes the next node.
484 ///Processes the next node. And checks that the given target node
485 ///is reached. If the target node is reachable from the processed
486 ///node then the reached parameter will be set true. The reached
487 ///parameter should be initially false.
489 ///\param target The target node.
490 ///\retval reached Indicates that the target node is reached.
491 ///\return The processed node.
493 ///\warning The queue must not be empty!
494 Node processNextNode(Node target, bool& reached)
496 if(_queue_tail==_queue_next_dist) {
498 _queue_next_dist=_queue_head;
500 Node n=_queue[_queue_tail++];
501 _processed->set(n,true);
503 for(OutEdgeIt e(*G,n);e!=INVALID;++e)
504 if(!(*_reached)[m=G->target(e)]) {
505 _queue[_queue_head++]=m;
506 _reached->set(m,true);
508 _dist->set(m,_curr_dist);
509 reached = reached || (target == m);
514 ///Processes the next node.
516 ///Processes the next node. And checks that at least one of
517 ///reached node has true value in the \c nm nodemap. If one node
518 ///with true value is reachable from the processed node then the
519 ///reached parameter will be set true. The reached parameter
520 ///should be initially false.
522 ///\param target The nodemaps of possible targets.
523 ///\retval reached Indicates that one of the target nodes is reached.
524 ///\return The processed node.
526 ///\warning The queue must not be empty!
528 Node processNextNode(const NM& nm, bool& reached)
530 if(_queue_tail==_queue_next_dist) {
532 _queue_next_dist=_queue_head;
534 Node n=_queue[_queue_tail++];
535 _processed->set(n,true);
537 for(OutEdgeIt e(*G,n);e!=INVALID;++e)
538 if(!(*_reached)[m=G->target(e)]) {
539 _queue[_queue_head++]=m;
540 _reached->set(m,true);
542 _dist->set(m,_curr_dist);
543 reached = reached || nm[m];
548 ///Next node to be processed.
550 ///Next node to be processed.
552 ///\return The next node to be processed or INVALID if the queue is
556 return _queue_tail<_queue_head?_queue[_queue_tail]:INVALID;
559 ///\brief Returns \c false if there are nodes
560 ///to be processed in the queue
562 ///Returns \c false if there are nodes
563 ///to be processed in the queue
564 bool emptyQueue() { return _queue_tail==_queue_head; }
565 ///Returns the number of the nodes to be processed.
567 ///Returns the number of the nodes to be processed in the queue.
569 int queueSize() { return _queue_head-_queue_tail; }
571 ///Executes the algorithm.
573 ///Executes the algorithm.
575 ///\pre init() must be called and at least one node should be added
576 ///with addSource() before using this function.
578 ///This method runs the %BFS algorithm from the root node(s)
581 ///shortest path to each node. The algorithm computes
582 ///- The shortest path tree.
583 ///- The distance of each node from the root(s).
587 while ( !emptyQueue() ) processNextNode();
590 ///Executes the algorithm until \c dest is reached.
592 ///Executes the algorithm until \c dest is reached.
594 ///\pre init() must be called and at least one node should be added
595 ///with addSource() before using this function.
597 ///This method runs the %BFS algorithm from the root node(s)
600 ///shortest path to \c dest. The algorithm computes
601 ///- The shortest path to \c dest.
602 ///- The distance of \c dest from the root(s).
604 void start(Node dest)
606 bool reached = false;
607 while ( !emptyQueue() && !reached) processNextNode(dest, reached);
610 ///Executes the algorithm until a condition is met.
612 ///Executes the algorithm until a condition is met.
614 ///\pre init() must be called and at least one node should be added
615 ///with addSource() before using this function.
617 ///\param nm must be a bool (or convertible) node map. The
618 ///algorithm will stop when it reached a node \c v with
619 ///<tt>nm[v]</tt> true.
620 ///\todo query the reached target
622 void start(const NM &nm)
624 bool reached = false;
625 while ( !emptyQueue() && !reached) processNextNode(nm, reached);
628 ///Runs %BFS algorithm from node \c s.
630 ///This method runs the %BFS algorithm from a root node \c s
633 ///shortest path to each node. The algorithm computes
634 ///- The shortest path tree.
635 ///- The distance of each node from the root.
637 ///\note b.run(s) is just a shortcut of the following code.
649 ///Finds the shortest path between \c s and \c t.
651 ///Finds the shortest path between \c s and \c t.
653 ///\return The length of the shortest s---t path if there exists one,
655 ///\note Apart from the return value, b.run(s) is
656 ///just a shortcut of the following code.
662 int run(Node s,Node t) {
666 return reached(t)? _curr_dist : 0;
671 ///\name Query Functions
672 ///The result of the %BFS algorithm can be obtained using these
674 ///Before the use of these functions,
675 ///either run() or start() must be calleb.
679 ///Copies the shortest path to \c t into \c p
681 ///This function copies the shortest path to \c t into \c p.
682 ///If \c t is a source itself or unreachable, then it does not
684 ///\return Returns \c true if a path to \c t was actually copied to \c p,
685 ///\c false otherwise.
688 bool getPath(P &p,Node t)
692 typename P::Builder b(p);
693 for(b.setStartNode(t);predEdge(t)!=INVALID;t=predNode(t))
694 b.pushFront(predEdge(t));
701 ///The distance of a node from the root(s).
703 ///Returns the distance of a node from the root(s).
704 ///\pre \ref run() must be called before using this function.
705 ///\warning If node \c v in unreachable from the root(s) the return value
706 ///of this function is undefined.
707 int dist(Node v) const { return (*_dist)[v]; }
709 ///Returns the 'previous edge' of the shortest path tree.
711 ///For a node \c v it returns the 'previous edge'
712 ///of the shortest path tree,
713 ///i.e. it returns the last edge of a shortest path from the root(s) to \c
714 ///v. It is \ref INVALID
715 ///if \c v is unreachable from the root(s) or \c v is a root. The
716 ///shortest path tree used here is equal to the shortest path tree used in
718 ///\pre Either \ref run() or \ref start() must be called before using
720 Edge predEdge(Node v) const { return (*_pred)[v];}
722 ///Returns the 'previous node' of the shortest path tree.
724 ///For a node \c v it returns the 'previous node'
725 ///of the shortest path tree,
726 ///i.e. it returns the last but one node from a shortest path from the
728 ///It is INVALID if \c v is unreachable from the root(s) or
729 ///if \c v itself a root.
730 ///The shortest path tree used here is equal to the shortest path
731 ///tree used in \ref predEdge().
732 ///\pre Either \ref run() or \ref start() must be called before
733 ///using this function.
734 Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
735 G->source((*_pred)[v]); }
737 ///Returns a reference to the NodeMap of distances.
739 ///Returns a reference to the NodeMap of distances.
740 ///\pre Either \ref run() or \ref init() must
741 ///be called before using this function.
742 const DistMap &distMap() const { return *_dist;}
744 ///Returns a reference to the shortest path tree map.
746 ///Returns a reference to the NodeMap of the edges of the
747 ///shortest path tree.
748 ///\pre Either \ref run() or \ref init()
749 ///must be called before using this function.
750 const PredMap &predMap() const { return *_pred;}
752 ///Checks if a node is reachable from the root.
754 ///Returns \c true if \c v is reachable from the root.
755 ///\warning The source nodes are indicated as unreached.
756 ///\pre Either \ref run() or \ref start()
757 ///must be called before using this function.
759 bool reached(Node v) { return (*_reached)[v]; }
764 ///Default traits class of Bfs function.
766 ///Default traits class of Bfs function.
767 ///\param GR Graph type.
769 struct BfsWizardDefaultTraits
771 ///The graph type the algorithm runs on.
773 ///\brief The type of the map that stores the last
774 ///edges of the shortest paths.
776 ///The type of the map that stores the last
777 ///edges of the shortest paths.
778 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
780 typedef NullMap<typename Graph::Node,typename GR::Edge> PredMap;
781 ///Instantiates a PredMap.
783 ///This function instantiates a \ref PredMap.
784 ///\param g is the graph, to which we would like to define the PredMap.
785 ///\todo The graph alone may be insufficient to initialize
787 static PredMap *createPredMap(const GR &g)
789 static PredMap *createPredMap(const GR &)
792 return new PredMap();
795 ///The type of the map that indicates which nodes are processed.
797 ///The type of the map that indicates which nodes are processed.
798 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
799 ///\todo named parameter to set this type, function to read and write.
800 typedef NullMap<typename Graph::Node,bool> ProcessedMap;
801 ///Instantiates a ProcessedMap.
803 ///This function instantiates a \ref ProcessedMap.
804 ///\param g is the graph, to which
805 ///we would like to define the \ref ProcessedMap
807 static ProcessedMap *createProcessedMap(const GR &g)
809 static ProcessedMap *createProcessedMap(const GR &)
812 return new ProcessedMap();
814 ///The type of the map that indicates which nodes are reached.
816 ///The type of the map that indicates which nodes are reached.
817 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
818 ///\todo named parameter to set this type, function to read and write.
819 typedef typename Graph::template NodeMap<bool> ReachedMap;
820 ///Instantiates a ReachedMap.
822 ///This function instantiates a \ref ReachedMap.
823 ///\param G is the graph, to which
824 ///we would like to define the \ref ReachedMap.
825 static ReachedMap *createReachedMap(const GR &G)
827 return new ReachedMap(G);
829 ///The type of the map that stores the dists of the nodes.
831 ///The type of the map that stores the dists of the nodes.
832 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
834 typedef NullMap<typename Graph::Node,int> DistMap;
835 ///Instantiates a DistMap.
837 ///This function instantiates a \ref DistMap.
838 ///\param g is the graph, to which we would like to define the \ref DistMap
840 static DistMap *createDistMap(const GR &g)
842 static DistMap *createDistMap(const GR &)
845 return new DistMap();
849 /// Default traits used by \ref BfsWizard
851 /// To make it easier to use Bfs algorithm
852 ///we have created a wizard class.
853 /// This \ref BfsWizard class needs default traits,
854 ///as well as the \ref Bfs class.
855 /// The \ref BfsWizardBase is a class to be the default traits of the
856 /// \ref BfsWizard class.
858 class BfsWizardBase : public BfsWizardDefaultTraits<GR>
861 typedef BfsWizardDefaultTraits<GR> Base;
863 /// Type of the nodes in the graph.
864 typedef typename Base::Graph::Node Node;
866 /// Pointer to the underlying graph.
868 ///Pointer to the map of reached nodes.
870 ///Pointer to the map of processed nodes.
872 ///Pointer to the map of predecessors edges.
874 ///Pointer to the map of distances.
876 ///Pointer to the source node.
882 /// This constructor does not require parameters, therefore it initiates
883 /// all of the attributes to default values (0, INVALID).
884 BfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0),
885 _dist(0), _source(INVALID) {}
889 /// This constructor requires some parameters,
890 /// listed in the parameters list.
891 /// Others are initiated to 0.
892 /// \param g is the initial value of \ref _g
893 /// \param s is the initial value of \ref _source
894 BfsWizardBase(const GR &g, Node s=INVALID) :
895 _g((void *)&g), _reached(0), _processed(0), _pred(0),
896 _dist(0), _source(s) {}
900 /// A class to make the usage of Bfs algorithm easier
902 /// This class is created to make it easier to use Bfs algorithm.
903 /// It uses the functions and features of the plain \ref Bfs,
904 /// but it is much simpler to use it.
906 /// Simplicity means that the way to change the types defined
907 /// in the traits class is based on functions that returns the new class
908 /// and not on templatable built-in classes.
909 /// When using the plain \ref Bfs
910 /// the new class with the modified type comes from
911 /// the original class by using the ::
912 /// operator. In the case of \ref BfsWizard only
913 /// a function have to be called and it will
914 /// return the needed class.
916 /// It does not have own \ref run method. When its \ref run method is called
917 /// it initiates a plain \ref Bfs class, and calls the \ref Bfs::run
920 class BfsWizard : public TR
924 ///The type of the underlying graph.
925 typedef typename TR::Graph Graph;
927 typedef typename Graph::Node Node;
929 typedef typename Graph::NodeIt NodeIt;
931 typedef typename Graph::Edge Edge;
933 typedef typename Graph::OutEdgeIt OutEdgeIt;
935 ///\brief The type of the map that stores
937 typedef typename TR::ReachedMap ReachedMap;
938 ///\brief The type of the map that stores
939 ///the processed nodes
940 typedef typename TR::ProcessedMap ProcessedMap;
941 ///\brief The type of the map that stores the last
942 ///edges of the shortest paths.
943 typedef typename TR::PredMap PredMap;
944 ///The type of the map that stores the dists of the nodes.
945 typedef typename TR::DistMap DistMap;
949 BfsWizard() : TR() {}
951 /// Constructor that requires parameters.
953 /// Constructor that requires parameters.
954 /// These parameters will be the default values for the traits class.
955 BfsWizard(const Graph &g, Node s=INVALID) :
959 BfsWizard(const TR &b) : TR(b) {}
963 ///Runs Bfs algorithm from a given node.
965 ///Runs Bfs algorithm from a given node.
966 ///The node can be given by the \ref source function.
969 if(Base::_source==INVALID) throw UninitializedParameter();
970 Bfs<Graph,TR> alg(*(Graph*)Base::_g);
972 alg.reachedMap(*(ReachedMap*)Base::_reached);
973 if(Base::_processed) alg.processedMap(*(ProcessedMap*)Base::_processed);
974 if(Base::_pred) alg.predMap(*(PredMap*)Base::_pred);
975 if(Base::_dist) alg.distMap(*(DistMap*)Base::_dist);
976 alg.run(Base::_source);
979 ///Runs Bfs algorithm from the given node.
981 ///Runs Bfs algorithm from the given node.
982 ///\param s is the given source.
990 struct DefPredMapBase : public Base {
992 static PredMap *createPredMap(const Graph &) { return 0; };
993 DefPredMapBase(const TR &b) : TR(b) {}
996 ///\brief \ref named-templ-param "Named parameter"
997 ///function for setting PredMap
999 /// \ref named-templ-param "Named parameter"
1000 ///function for setting PredMap
1003 BfsWizard<DefPredMapBase<T> > predMap(const T &t)
1005 Base::_pred=(void *)&t;
1006 return BfsWizard<DefPredMapBase<T> >(*this);
1011 struct DefReachedMapBase : public Base {
1012 typedef T ReachedMap;
1013 static ReachedMap *createReachedMap(const Graph &) { return 0; };
1014 DefReachedMapBase(const TR &b) : TR(b) {}
1017 ///\brief \ref named-templ-param "Named parameter"
1018 ///function for setting ReachedMap
1020 /// \ref named-templ-param "Named parameter"
1021 ///function for setting ReachedMap
1024 BfsWizard<DefReachedMapBase<T> > reachedMap(const T &t)
1026 Base::_pred=(void *)&t;
1027 return BfsWizard<DefReachedMapBase<T> >(*this);
1032 struct DefProcessedMapBase : public Base {
1033 typedef T ProcessedMap;
1034 static ProcessedMap *createProcessedMap(const Graph &) { return 0; };
1035 DefProcessedMapBase(const TR &b) : TR(b) {}
1038 ///\brief \ref named-templ-param "Named parameter"
1039 ///function for setting ProcessedMap
1041 /// \ref named-templ-param "Named parameter"
1042 ///function for setting ProcessedMap
1045 BfsWizard<DefProcessedMapBase<T> > processedMap(const T &t)
1047 Base::_pred=(void *)&t;
1048 return BfsWizard<DefProcessedMapBase<T> >(*this);
1053 struct DefDistMapBase : public Base {
1055 static DistMap *createDistMap(const Graph &) { return 0; };
1056 DefDistMapBase(const TR &b) : TR(b) {}
1059 ///\brief \ref named-templ-param "Named parameter"
1060 ///function for setting DistMap type
1062 /// \ref named-templ-param "Named parameter"
1063 ///function for setting DistMap type
1066 BfsWizard<DefDistMapBase<T> > distMap(const T &t)
1068 Base::_dist=(void *)&t;
1069 return BfsWizard<DefDistMapBase<T> >(*this);
1072 /// Sets the source node, from which the Bfs algorithm runs.
1074 /// Sets the source node, from which the Bfs algorithm runs.
1075 /// \param s is the source node.
1076 BfsWizard<TR> &source(Node s)
1084 ///Function type interface for Bfs algorithm.
1086 /// \ingroup flowalgs
1087 ///Function type interface for Bfs algorithm.
1089 ///This function also has several
1090 ///\ref named-templ-func-param "named parameters",
1091 ///they are declared as the members of class \ref BfsWizard.
1093 ///example shows how to use these parameters.
1095 /// bfs(g,source).predMap(preds).run();
1097 ///\warning Don't forget to put the \ref BfsWizard::run() "run()"
1098 ///to the end of the parameter list.
1102 BfsWizard<BfsWizardBase<GR> >
1103 bfs(const GR &g,typename GR::Node s=INVALID)
1105 return BfsWizard<BfsWizardBase<GR> >(g,s);
1109 /// \brief Visitor class for bfs.
1111 /// It gives a simple interface for a functional interface for bfs
1112 /// traversal. The traversal on a linear data structure.
1113 template <typename _Graph>
1115 typedef _Graph Graph;
1116 typedef typename Graph::Edge Edge;
1117 typedef typename Graph::Node Node;
1118 /// \brief Called when the edge reach a node.
1120 /// It is called when the bfs find an edge which target is not
1122 void discover(const Edge& edge) {}
1123 /// \brief Called when the node reached first time.
1125 /// It is Called when the node reached first time.
1126 void reach(const Node& node) {}
1127 /// \brief Called when the edge examined but target of the edge
1128 /// already discovered.
1130 /// It called when the edge examined but the target of the edge
1131 /// already discovered.
1132 void examine(const Edge& edge) {}
1133 /// \brief Called for the source node of the bfs.
1135 /// It is called for the source node of the bfs.
1136 void start(const Node& node) {}
1137 /// \brief Called when the node processed.
1139 /// It is Called when the node processed.
1140 void process(const Node& node) {}
1143 template <typename _Graph>
1145 typedef _Graph Graph;
1146 typedef typename Graph::Edge Edge;
1147 typedef typename Graph::Node Node;
1148 void discover(const Edge&) {}
1149 void reach(const Node&) {}
1150 void examine(const Edge&) {}
1151 void start(const Node&) {}
1152 void process(const Node&) {}
1154 template <typename _Visitor>
1155 struct Constraints {
1156 void constraints() {
1159 visitor.discover(edge);
1160 visitor.reach(node);
1161 visitor.examine(edge);
1162 visitor.start(node);
1163 visitor.process(node);
1170 /// \brief Default traits class of BfsVisit class.
1172 /// Default traits class of BfsVisit class.
1173 /// \param _Graph Graph type.
1174 template<class _Graph>
1175 struct BfsVisitDefaultTraits {
1177 /// \brief The graph type the algorithm runs on.
1178 typedef _Graph Graph;
1180 /// \brief The type of the map that indicates which nodes are reached.
1182 /// The type of the map that indicates which nodes are reached.
1183 /// It must meet the \ref concepts::WriteMap "WriteMap" concept.
1184 /// \todo named parameter to set this type, function to read and write.
1185 typedef typename Graph::template NodeMap<bool> ReachedMap;
1187 /// \brief Instantiates a ReachedMap.
1189 /// This function instantiates a \ref ReachedMap.
1190 /// \param graph is the graph, to which
1191 /// we would like to define the \ref ReachedMap.
1192 static ReachedMap *createReachedMap(const Graph &graph) {
1193 return new ReachedMap(graph);
1198 /// %BFS Visit algorithm class.
1200 /// \ingroup flowalgs
1201 /// This class provides an efficient implementation of the %BFS algorithm
1202 /// with visitor interface.
1204 /// The %BfsVisit class provides an alternative interface to the Bfs
1205 /// class. It works with callback mechanism, the BfsVisit object calls
1206 /// on every bfs event the \c Visitor class member functions.
1208 /// \param _Graph The graph type the algorithm runs on. The default value is
1209 /// \ref ListGraph. The value of _Graph is not used directly by Bfs, it
1210 /// is only passed to \ref BfsDefaultTraits.
1211 /// \param _Visitor The Visitor object for the algorithm. The
1212 /// \ref BfsVisitor "BfsVisitor<_Graph>" is an empty Visitor which
1213 /// does not observe the Bfs events. If you want to observe the bfs
1214 /// events you should implement your own Visitor class.
1215 /// \param _Traits Traits class to set various data types used by the
1216 /// algorithm. The default traits class is
1217 /// \ref BfsVisitDefaultTraits "BfsVisitDefaultTraits<_Graph>".
1218 /// See \ref BfsVisitDefaultTraits for the documentation of
1219 /// a Bfs visit traits class.
1221 /// \author Jacint Szabo, Alpar Juttner and Balazs Dezso
1223 template <typename _Graph, typename _Visitor, typename _Traits>
1225 template <typename _Graph = ListGraph,
1226 typename _Visitor = BfsVisitor<_Graph>,
1227 typename _Traits = BfsDefaultTraits<_Graph> >
1232 /// \brief \ref Exception for uninitialized parameters.
1234 /// This error represents problems in the initialization
1235 /// of the parameters of the algorithms.
1236 class UninitializedParameter : public lemon::UninitializedParameter {
1238 virtual const char* what() const throw()
1240 return "lemon::BfsVisit::UninitializedParameter";
1244 typedef _Traits Traits;
1246 typedef typename Traits::Graph Graph;
1248 typedef _Visitor Visitor;
1250 ///The type of the map indicating which nodes are reached.
1251 typedef typename Traits::ReachedMap ReachedMap;
1255 typedef typename Graph::Node Node;
1256 typedef typename Graph::NodeIt NodeIt;
1257 typedef typename Graph::Edge Edge;
1258 typedef typename Graph::OutEdgeIt OutEdgeIt;
1260 /// Pointer to the underlying graph.
1261 const Graph *_graph;
1262 /// Pointer to the visitor object.
1264 ///Pointer to the map of reached status of the nodes.
1265 ReachedMap *_reached;
1266 ///Indicates if \ref _reached is locally allocated (\c true) or not.
1269 std::vector<typename Graph::Node> _list;
1270 int _list_front, _list_back;
1272 /// \brief Creates the maps if necessary.
1274 /// Creates the maps if necessary.
1275 void create_maps() {
1277 local_reached = true;
1278 _reached = Traits::createReachedMap(*_graph);
1288 typedef BfsVisit Create;
1290 /// \name Named template parameters
1294 struct DefReachedMapTraits : public Traits {
1295 typedef T ReachedMap;
1296 static ReachedMap *createReachedMap(const Graph &graph) {
1297 throw UninitializedParameter();
1300 /// \brief \ref named-templ-param "Named parameter" for setting
1303 /// \ref named-templ-param "Named parameter" for setting ReachedMap type
1305 struct DefReachedMap : public BfsVisit< Graph, Visitor,
1306 DefReachedMapTraits<T> > {
1307 typedef BfsVisit< Graph, Visitor, DefReachedMapTraits<T> > Create;
1313 /// \brief Constructor.
1317 /// \param graph the graph the algorithm will run on.
1318 /// \param visitor The visitor of the algorithm.
1320 BfsVisit(const Graph& graph, Visitor& visitor)
1321 : _graph(&graph), _visitor(&visitor),
1322 _reached(0), local_reached(false) {}
1324 /// \brief Destructor.
1328 if(local_reached) delete _reached;
1331 /// \brief Sets the map indicating if a node is reached.
1333 /// Sets the map indicating if a node is reached.
1334 /// If you don't use this function before calling \ref run(),
1335 /// it will allocate one. The destuctor deallocates this
1336 /// automatically allocated map, of course.
1337 /// \return <tt> (*this) </tt>
1338 BfsVisit &reachedMap(ReachedMap &m) {
1341 local_reached = false;
1348 /// \name Execution control
1349 /// The simplest way to execute the algorithm is to use
1350 /// one of the member functions called \c run(...).
1352 /// If you need more control on the execution,
1353 /// first you must call \ref init(), then you can adda source node
1354 /// with \ref addSource().
1355 /// Finally \ref start() will perform the actual path
1359 /// \brief Initializes the internal data structures.
1361 /// Initializes the internal data structures.
1365 _list.resize(countNodes(*_graph));
1366 _list_front = _list_back = -1;
1367 for (NodeIt u(*_graph) ; u != INVALID ; ++u) {
1368 _reached->set(u, false);
1372 /// \brief Adds a new source node.
1374 /// Adds a new source node to the set of nodes to be processed.
1375 void addSource(Node s) {
1376 if(!(*_reached)[s]) {
1377 _reached->set(s,true);
1380 _list[++_list_back] = s;
1384 /// \brief Processes the next node.
1386 /// Processes the next node.
1388 /// \return The processed node.
1390 /// \pre The queue must not be empty!
1391 Node processNextNode() {
1392 Node n = _list[++_list_front];
1393 _visitor->process(n);
1395 for (_graph->firstOut(e, n); e != INVALID; _graph->nextOut(e)) {
1396 Node m = _graph->target(e);
1397 if (!(*_reached)[m]) {
1398 _visitor->discover(e);
1400 _reached->set(m, true);
1401 _list[++_list_back] = m;
1403 _visitor->examine(e);
1409 /// \brief Processes the next node.
1411 /// Processes the next node. And checks that the given target node
1412 /// is reached. If the target node is reachable from the processed
1413 /// node then the reached parameter will be set true. The reached
1414 /// parameter should be initially false.
1416 /// \param target The target node.
1417 /// \retval reached Indicates that the target node is reached.
1418 /// \return The processed node.
1420 /// \warning The queue must not be empty!
1421 Node processNextNode(Node target, bool& reached) {
1422 Node n = _list[++_list_front];
1423 _visitor->process(n);
1425 for (_graph->firstOut(e, n); e != INVALID; _graph->nextOut(e)) {
1426 Node m = _graph->target(e);
1427 if (!(*_reached)[m]) {
1428 _visitor->discover(e);
1430 _reached->set(m, true);
1431 _list[++_list_back] = m;
1432 reached = reached || (target == m);
1434 _visitor->examine(e);
1440 /// \brief Processes the next node.
1442 /// Processes the next node. And checks that at least one of
1443 /// reached node has true value in the \c nm nodemap. If one node
1444 /// with true value is reachable from the processed node then the
1445 /// reached parameter will be set true. The reached parameter
1446 /// should be initially false.
1448 /// \param target The nodemaps of possible targets.
1449 /// \retval reached Indicates that one of the target nodes is reached.
1450 /// \return The processed node.
1452 /// \warning The queue must not be empty!
1453 template <typename NM>
1454 Node processNextNode(const NM& nm, bool& reached) {
1455 Node n = _list[++_list_front];
1456 _visitor->process(n);
1458 for (_graph->firstOut(e, n); e != INVALID; _graph->nextOut(e)) {
1459 Node m = _graph->target(e);
1460 if (!(*_reached)[m]) {
1461 _visitor->discover(e);
1463 _reached->set(m, true);
1464 _list[++_list_back] = m;
1465 reached = reached || nm[m];
1467 _visitor->examine(e);
1473 /// \brief Next node to be processed.
1475 /// Next node to be processed.
1477 /// \return The next node to be processed or INVALID if the stack is
1480 return _list_front != _list_back ? _list[_list_front + 1] : INVALID;
1483 /// \brief Returns \c false if there are nodes
1484 /// to be processed in the queue
1486 /// Returns \c false if there are nodes
1487 /// to be processed in the queue
1488 bool emptyQueue() { return _list_front == _list_back; }
1490 /// \brief Returns the number of the nodes to be processed.
1492 /// Returns the number of the nodes to be processed in the queue.
1493 int queueSize() { return _list_back - _list_front; }
1495 /// \brief Executes the algorithm.
1497 /// Executes the algorithm.
1499 /// \pre init() must be called and at least one node should be added
1500 /// with addSource() before using this function.
1502 while ( !emptyQueue() ) processNextNode();
1505 /// \brief Executes the algorithm until \c dest is reached.
1507 /// Executes the algorithm until \c dest is reached.
1509 /// \pre init() must be called and at least one node should be added
1510 /// with addSource() before using this function.
1511 void start(Node dest) {
1512 bool reached = false;
1513 while (!emptyQueue() && !reached) {
1514 processNextNode(dest, reached);
1518 /// \brief Executes the algorithm until a condition is met.
1520 /// Executes the algorithm until a condition is met.
1522 /// \pre init() must be called and at least one node should be added
1523 /// with addSource() before using this function.
1525 ///\param nm must be a bool (or convertible) node map. The
1526 ///algorithm will stop when it reached a node \c v with
1527 ///<tt>nm[v]</tt> true.
1528 template <typename NM>
1529 void start(const NM &nm) {
1530 bool reached = false;
1531 while (!emptyQueue() && !reached) {
1532 processNextNode(nm, reached);
1536 /// \brief Runs %BFSVisit algorithm from node \c s.
1538 /// This method runs the %BFS algorithm from a root node \c s.
1539 /// \note b.run(s) is just a shortcut of the following code.
1551 /// \brief Runs %BFSVisit algorithm to visit all nodes in the graph.
1553 /// This method runs the %BFS algorithm in order to
1554 /// compute the %BFS path to each node. The algorithm computes
1555 /// - The %BFS tree.
1556 /// - The distance of each node from the root in the %BFS tree.
1558 ///\note b.run() is just a shortcut of the following code.
1561 /// for (NodeIt it(graph); it != INVALID; ++it) {
1562 /// if (!b.reached(it)) {
1563 /// b.addSource(it);
1570 for (NodeIt it(*_graph); it != INVALID; ++it) {
1579 /// \name Query Functions
1580 /// The result of the %BFS algorithm can be obtained using these
1582 /// Before the use of these functions,
1583 /// either run() or start() must be called.
1586 /// \brief Checks if a node is reachable from the root.
1588 /// Returns \c true if \c v is reachable from the root(s).
1589 /// \warning The source nodes are inditated as unreachable.
1590 /// \pre Either \ref run() or \ref start()
1591 /// must be called before using this function.
1593 bool reached(Node v) { return (*_reached)[v]; }
1597 } //END OF NAMESPACE LEMON