3 * This file is a part of LEMON, a generic C++ optimization library
5 * Copyright (C) 2003-2007
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/path_dump.h>
29 #include <lemon/bits/invalid.h>
30 #include <lemon/error.h>
31 #include <lemon/maps.h>
37 ///Default traits class of Bfs class.
39 ///Default traits class of Bfs class.
40 ///\param GR Graph type.
42 struct BfsDefaultTraits
44 ///The graph type the algorithm runs on.
46 ///\brief The type of the map that stores the last
47 ///edges of the shortest paths.
49 ///The type of the map that stores the last
50 ///edges of the shortest paths.
51 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
53 typedef typename Graph::template NodeMap<typename GR::Edge> PredMap;
54 ///Instantiates a PredMap.
56 ///This function instantiates a \ref PredMap.
57 ///\param G is the graph, to which we would like to define the PredMap.
58 ///\todo The graph alone may be insufficient to initialize
59 static PredMap *createPredMap(const GR &G)
61 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 ///\todo named parameter to set this type, function to read and write.
68 typedef NullMap<typename Graph::Node,bool> ProcessedMap;
69 ///Instantiates a ProcessedMap.
71 ///This function instantiates a \ref ProcessedMap.
72 ///\param g is the graph, to which
73 ///we would like to define the \ref ProcessedMap
75 static ProcessedMap *createProcessedMap(const GR &g)
77 static ProcessedMap *createProcessedMap(const GR &)
80 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::WriteMap "WriteMap" concept.
86 ///\todo named parameter to set this type, function to read and write.
87 typedef typename Graph::template NodeMap<bool> ReachedMap;
88 ///Instantiates a ReachedMap.
90 ///This function instantiates a \ref ReachedMap.
91 ///\param G is the graph, to which
92 ///we would like to define the \ref ReachedMap.
93 static ReachedMap *createReachedMap(const GR &G)
95 return new ReachedMap(G);
97 ///The type of the map that stores the dists of the nodes.
99 ///The type of the map that stores the dists of the nodes.
100 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
102 typedef typename Graph::template NodeMap<int> DistMap;
103 ///Instantiates a DistMap.
105 ///This function instantiates a \ref DistMap.
106 ///\param G is the graph, to which we would like to define the \ref DistMap
107 static DistMap *createDistMap(const GR &G)
109 return new DistMap(G);
113 ///%BFS algorithm class.
116 ///This class provides an efficient implementation of the %BFS algorithm.
118 ///\param GR The graph type the algorithm runs on. The default value is
119 ///\ref ListGraph. The value of GR is not used directly by Bfs, it
120 ///is only passed to \ref BfsDefaultTraits.
121 ///\param TR Traits class to set various data types used by the algorithm.
122 ///The default traits class is
123 ///\ref BfsDefaultTraits "BfsDefaultTraits<GR>".
124 ///See \ref BfsDefaultTraits for the documentation of
125 ///a Bfs traits class.
127 ///\author Alpar Juttner
130 template <typename GR,
133 template <typename GR=ListGraph,
134 typename TR=BfsDefaultTraits<GR> >
139 * \brief \ref Exception for uninitialized parameters.
141 * This error represents problems in the initialization
142 * of the parameters of the algorithms.
144 class UninitializedParameter : public lemon::UninitializedParameter {
146 virtual const char* what() const throw() {
147 return "lemon::Bfs::UninitializedParameter";
152 ///The type of the underlying graph.
153 typedef typename TR::Graph Graph;
155 typedef typename Graph::Node Node;
157 typedef typename Graph::NodeIt NodeIt;
159 typedef typename Graph::Edge Edge;
161 typedef typename Graph::OutEdgeIt OutEdgeIt;
163 ///\brief The type of the map that stores the last
164 ///edges of the shortest paths.
165 typedef typename TR::PredMap PredMap;
166 ///The type of the map indicating which nodes are reached.
167 typedef typename TR::ReachedMap ReachedMap;
168 ///The type of the map indicating which nodes are processed.
169 typedef typename TR::ProcessedMap ProcessedMap;
170 ///The type of the map that stores the dists of the nodes.
171 typedef typename TR::DistMap DistMap;
173 /// Pointer to the underlying graph.
175 ///Pointer to the map of predecessors edges.
177 ///Indicates if \ref _pred is locally allocated (\c true) or not.
179 ///Pointer to the map of distances.
181 ///Indicates if \ref _dist is locally allocated (\c true) or not.
183 ///Pointer to the map of reached status of the nodes.
184 ReachedMap *_reached;
185 ///Indicates if \ref _reached is locally allocated (\c true) or not.
187 ///Pointer to the map of processed status of the nodes.
188 ProcessedMap *_processed;
189 ///Indicates if \ref _processed is locally allocated (\c true) or not.
190 bool local_processed;
192 std::vector<typename Graph::Node> _queue;
193 int _queue_head,_queue_tail,_queue_next_dist;
196 ///Creates the maps if necessary.
198 ///\todo Better memory allocation (instead of new).
203 _pred = Traits::createPredMap(*G);
207 _dist = Traits::createDistMap(*G);
210 local_reached = true;
211 _reached = Traits::createReachedMap(*G);
214 local_processed = true;
215 _processed = Traits::createProcessedMap(*G);
227 ///\name Named template parameters
232 struct DefPredMapTraits : public Traits {
234 static PredMap *createPredMap(const Graph &)
236 throw UninitializedParameter();
239 ///\ref named-templ-param "Named parameter" for setting PredMap type
241 ///\ref named-templ-param "Named parameter" for setting PredMap type
244 struct DefPredMap : public Bfs< Graph, DefPredMapTraits<T> > {
245 typedef Bfs< Graph, DefPredMapTraits<T> > Create;
249 struct DefDistMapTraits : public Traits {
251 static DistMap *createDistMap(const Graph &)
253 throw UninitializedParameter();
256 ///\ref named-templ-param "Named parameter" for setting DistMap type
258 ///\ref named-templ-param "Named parameter" for setting DistMap type
261 struct DefDistMap : public Bfs< Graph, DefDistMapTraits<T> > {
262 typedef Bfs< Graph, DefDistMapTraits<T> > Create;
266 struct DefReachedMapTraits : public Traits {
267 typedef T ReachedMap;
268 static ReachedMap *createReachedMap(const Graph &)
270 throw UninitializedParameter();
273 ///\ref named-templ-param "Named parameter" for setting ReachedMap type
275 ///\ref named-templ-param "Named parameter" for setting ReachedMap type
278 struct DefReachedMap : public Bfs< Graph, DefReachedMapTraits<T> > {
279 typedef Bfs< Graph, DefReachedMapTraits<T> > Create;
283 struct DefProcessedMapTraits : public Traits {
284 typedef T ProcessedMap;
285 static ProcessedMap *createProcessedMap(const Graph &)
287 throw UninitializedParameter();
290 ///\ref named-templ-param "Named parameter" for setting ProcessedMap type
292 ///\ref named-templ-param "Named parameter" for setting ProcessedMap type
295 struct DefProcessedMap : public Bfs< Graph, DefProcessedMapTraits<T> > {
296 typedef Bfs< Graph, DefProcessedMapTraits<T> > Create;
299 struct DefGraphProcessedMapTraits : public Traits {
300 typedef typename Graph::template NodeMap<bool> ProcessedMap;
301 static ProcessedMap *createProcessedMap(const Graph &G)
303 return new ProcessedMap(G);
306 ///\brief \ref named-templ-param "Named parameter"
307 ///for setting the ProcessedMap type to be Graph::NodeMap<bool>.
309 ///\ref named-templ-param "Named parameter"
310 ///for setting the ProcessedMap type to be Graph::NodeMap<bool>.
311 ///If you don't set it explicitly, it will be automatically allocated.
313 struct DefProcessedMapToBeDefaultMap :
314 public Bfs< Graph, DefGraphProcessedMapTraits> {
315 typedef Bfs< Graph, DefGraphProcessedMapTraits> Create;
324 ///\param _G the graph the algorithm will run on.
326 Bfs(const Graph& _G) :
328 _pred(NULL), local_pred(false),
329 _dist(NULL), local_dist(false),
330 _reached(NULL), local_reached(false),
331 _processed(NULL), local_processed(false)
337 if(local_pred) delete _pred;
338 if(local_dist) delete _dist;
339 if(local_reached) delete _reached;
340 if(local_processed) delete _processed;
343 ///Sets the map storing the predecessor edges.
345 ///Sets the map storing the predecessor edges.
346 ///If you don't use this function before calling \ref run(),
347 ///it will allocate one. The destructor deallocates this
348 ///automatically allocated map, of course.
349 ///\return <tt> (*this) </tt>
350 Bfs &predMap(PredMap &m)
360 ///Sets the map indicating the reached nodes.
362 ///Sets the map indicating the reached nodes.
363 ///If you don't use this function before calling \ref run(),
364 ///it will allocate one. The destructor deallocates this
365 ///automatically allocated map, of course.
366 ///\return <tt> (*this) </tt>
367 Bfs &reachedMap(ReachedMap &m)
377 ///Sets the map indicating the processed nodes.
379 ///Sets the map indicating the processed nodes.
380 ///If you don't use this function before calling \ref run(),
381 ///it will allocate one. The destructor deallocates this
382 ///automatically allocated map, of course.
383 ///\return <tt> (*this) </tt>
384 Bfs &processedMap(ProcessedMap &m)
386 if(local_processed) {
388 local_processed=false;
394 ///Sets the map storing the distances calculated by the algorithm.
396 ///Sets the map storing the distances calculated by the algorithm.
397 ///If you don't use this function before calling \ref run(),
398 ///it will allocate one. The destructor deallocates this
399 ///automatically allocated map, of course.
400 ///\return <tt> (*this) </tt>
401 Bfs &distMap(DistMap &m)
412 ///\name Execution control
413 ///The simplest way to execute the algorithm is to use
414 ///one of the member functions called \c run(...).
416 ///If you need more control on the execution,
417 ///first you must call \ref init(), then you can add several source nodes
418 ///with \ref addSource().
419 ///Finally \ref start() will perform the actual path
424 ///Initializes the internal data structures.
426 ///Initializes the internal data structures.
431 _queue.resize(countNodes(*G));
432 _queue_head=_queue_tail=0;
434 for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
435 _pred->set(u,INVALID);
436 _reached->set(u,false);
437 _processed->set(u,false);
441 ///Adds a new source node.
443 ///Adds a new source node to the set of nodes to be processed.
445 void addSource(Node s)
449 _reached->set(s,true);
450 _pred->set(s,INVALID);
452 _queue[_queue_head++]=s;
453 _queue_next_dist=_queue_head;
457 ///Processes the next node.
459 ///Processes the next node.
461 ///\return The processed node.
463 ///\warning The queue must not be empty!
464 Node processNextNode()
466 if(_queue_tail==_queue_next_dist) {
468 _queue_next_dist=_queue_head;
470 Node n=_queue[_queue_tail++];
471 _processed->set(n,true);
473 for(OutEdgeIt e(*G,n);e!=INVALID;++e)
474 if(!(*_reached)[m=G->target(e)]) {
475 _queue[_queue_head++]=m;
476 _reached->set(m,true);
478 _dist->set(m,_curr_dist);
483 ///Processes the next node.
485 ///Processes the next node. And checks that the given target node
486 ///is reached. If the target node is reachable from the processed
487 ///node then the reached parameter will be set true. The reached
488 ///parameter should be initially false.
490 ///\param target The target node.
491 ///\retval reach Indicates that the target node is reached.
492 ///\return The processed node.
494 ///\warning The queue must not be empty!
495 Node processNextNode(Node target, bool& reach)
497 if(_queue_tail==_queue_next_dist) {
499 _queue_next_dist=_queue_head;
501 Node n=_queue[_queue_tail++];
502 _processed->set(n,true);
504 for(OutEdgeIt e(*G,n);e!=INVALID;++e)
505 if(!(*_reached)[m=G->target(e)]) {
506 _queue[_queue_head++]=m;
507 _reached->set(m,true);
509 _dist->set(m,_curr_dist);
510 reach = reach || (target == m);
515 ///Processes the next node.
517 ///Processes the next node. And checks that at least one of
518 ///reached node has true value in the \c nm node map. If one node
519 ///with true value is reachable from the processed node then the
520 ///rnode parameter will be set to the first of such nodes.
522 ///\param nm The node map of possible targets.
523 ///\retval rnode The reached target node.
524 ///\return The processed node.
526 ///\warning The queue must not be empty!
528 Node processNextNode(const NM& nm, Node& rnode)
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 if (nm[m] && rnode == INVALID) rnode = 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.
568 int queueSize() { return _queue_head-_queue_tail; }
570 ///Executes the algorithm.
572 ///Executes the algorithm.
574 ///\pre init() must be called and at least one node should be added
575 ///with addSource() before using this function.
577 ///This method runs the %BFS algorithm from the root node(s)
580 ///shortest path to each node. The algorithm computes
581 ///- The shortest path tree.
582 ///- The distance of each node from the root(s).
585 while ( !emptyQueue() ) processNextNode();
588 ///Executes the algorithm until \c dest is reached.
590 ///Executes the algorithm until \c dest is reached.
592 ///\pre init() must be called and at least one node should be added
593 ///with addSource() before using this function.
595 ///This method runs the %BFS algorithm from the root node(s)
596 ///in order to compute the shortest path to \c dest.
597 ///The algorithm computes
598 ///- The shortest path to \c dest.
599 ///- The distance of \c dest from the root(s).
600 void start(Node dest)
603 while ( !emptyQueue() && !reach ) processNextNode(dest, reach);
606 ///Executes the algorithm until a condition is met.
608 ///Executes the algorithm until a condition is met.
610 ///\pre init() must be called and at least one node should be added
611 ///with addSource() before using this function.
613 ///\param nm must be a bool (or convertible) node map. The
614 ///algorithm will stop when it reaches a node \c v with
615 /// <tt>nm[v]</tt> true.
617 ///\return The reached node \c v with <tt>nm[v]</tt> true or
618 ///\c INVALID if no such node was found.
620 Node start(const NM &nm)
622 Node rnode = INVALID;
623 while ( !emptyQueue() && rnode == INVALID ) {
624 processNextNode(nm, rnode);
629 ///Runs %BFS algorithm from node \c s.
631 ///This method runs the %BFS algorithm from a root node \c s
634 ///shortest path to each node. The algorithm computes
635 ///- The shortest path tree.
636 ///- The distance of each node from the root.
638 ///\note b.run(s) is just a shortcut of the following code.
650 ///Finds the shortest path between \c s and \c t.
652 ///Finds the shortest path between \c s and \c t.
654 ///\return The length of the shortest s---t path if there exists one,
656 ///\note Apart from the return value, b.run(s) is
657 ///just a shortcut of the following code.
663 int run(Node s,Node t) {
667 return reached(t) ? _curr_dist : 0;
672 ///\name Query Functions
673 ///The result of the %BFS algorithm can be obtained using these
675 ///Before the use of these functions,
676 ///either run() or start() must be calleb.
680 typedef PredMapPath<Graph, PredMap> Path;
682 ///Gives back the shortest path.
684 ///Gives back the shortest path.
685 ///\pre The \c t should be reachable from the source.
688 return Path(*G, *_pred, t);
691 ///The distance of a node from the root(s).
693 ///Returns the distance of a node from the root(s).
694 ///\pre \ref run() must be called before using this function.
695 ///\warning If node \c v in unreachable from the root(s) the return value
696 ///of this function is undefined.
697 int dist(Node v) const { return (*_dist)[v]; }
699 ///Returns the 'previous edge' of the shortest path tree.
701 ///For a node \c v it returns the 'previous edge'
702 ///of the shortest path tree,
703 ///i.e. it returns the last edge of a shortest path from the root(s) to \c
704 ///v. It is \ref INVALID
705 ///if \c v is unreachable from the root(s) or \c v is a root. The
706 ///shortest path tree used here is equal to the shortest path tree used in
708 ///\pre Either \ref run() or \ref start() must be called before using
710 Edge predEdge(Node v) const { return (*_pred)[v];}
712 ///Returns the 'previous node' of the shortest path tree.
714 ///For a node \c v it returns the 'previous node'
715 ///of the shortest path tree,
716 ///i.e. it returns the last but one node from a shortest path from the
718 ///It is INVALID if \c v is unreachable from the root(s) or
719 ///if \c v itself a root.
720 ///The shortest path tree used here is equal to the shortest path
721 ///tree used in \ref predEdge().
722 ///\pre Either \ref run() or \ref start() must be called before
723 ///using this function.
724 Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
725 G->source((*_pred)[v]); }
727 ///Returns a reference to the NodeMap of distances.
729 ///Returns a reference to the NodeMap of distances.
730 ///\pre Either \ref run() or \ref init() must
731 ///be called before using this function.
732 const DistMap &distMap() const { return *_dist;}
734 ///Returns a reference to the shortest path tree map.
736 ///Returns a reference to the NodeMap of the edges of the
737 ///shortest path tree.
738 ///\pre Either \ref run() or \ref init()
739 ///must be called before using this function.
740 const PredMap &predMap() const { return *_pred;}
742 ///Checks if a node is reachable from the root.
744 ///Returns \c true if \c v is reachable from the root.
745 ///\warning The source nodes are indicated as unreached.
746 ///\pre Either \ref run() or \ref start()
747 ///must be called before using this function.
749 bool reached(Node v) { return (*_reached)[v]; }
754 ///Default traits class of Bfs function.
756 ///Default traits class of Bfs function.
757 ///\param GR Graph type.
759 struct BfsWizardDefaultTraits
761 ///The graph type the algorithm runs on.
763 ///\brief The type of the map that stores the last
764 ///edges of the shortest paths.
766 ///The type of the map that stores the last
767 ///edges of the shortest paths.
768 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
770 typedef NullMap<typename Graph::Node,typename GR::Edge> PredMap;
771 ///Instantiates a PredMap.
773 ///This function instantiates a \ref PredMap.
774 ///\param g is the graph, to which we would like to define the PredMap.
775 ///\todo The graph alone may be insufficient to initialize
777 static PredMap *createPredMap(const GR &g)
779 static PredMap *createPredMap(const GR &)
782 return new PredMap();
785 ///The type of the map that indicates which nodes are processed.
787 ///The type of the map that indicates which nodes are processed.
788 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
789 ///\todo named parameter to set this type, function to read and write.
790 typedef NullMap<typename Graph::Node,bool> ProcessedMap;
791 ///Instantiates a ProcessedMap.
793 ///This function instantiates a \ref ProcessedMap.
794 ///\param g is the graph, to which
795 ///we would like to define the \ref ProcessedMap
797 static ProcessedMap *createProcessedMap(const GR &g)
799 static ProcessedMap *createProcessedMap(const GR &)
802 return new ProcessedMap();
804 ///The type of the map that indicates which nodes are reached.
806 ///The type of the map that indicates which nodes are reached.
807 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
808 ///\todo named parameter to set this type, function to read and write.
809 typedef typename Graph::template NodeMap<bool> ReachedMap;
810 ///Instantiates a ReachedMap.
812 ///This function instantiates a \ref ReachedMap.
813 ///\param G is the graph, to which
814 ///we would like to define the \ref ReachedMap.
815 static ReachedMap *createReachedMap(const GR &G)
817 return new ReachedMap(G);
819 ///The type of the map that stores the dists of the nodes.
821 ///The type of the map that stores the dists of the nodes.
822 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
824 typedef NullMap<typename Graph::Node,int> DistMap;
825 ///Instantiates a DistMap.
827 ///This function instantiates a \ref DistMap.
828 ///\param g is the graph, to which we would like to define the \ref DistMap
830 static DistMap *createDistMap(const GR &g)
832 static DistMap *createDistMap(const GR &)
835 return new DistMap();
839 /// Default traits used by \ref BfsWizard
841 /// To make it easier to use Bfs algorithm
842 ///we have created a wizard class.
843 /// This \ref BfsWizard class needs default traits,
844 ///as well as the \ref Bfs class.
845 /// The \ref BfsWizardBase is a class to be the default traits of the
846 /// \ref BfsWizard class.
848 class BfsWizardBase : public BfsWizardDefaultTraits<GR>
851 typedef BfsWizardDefaultTraits<GR> Base;
853 /// Type of the nodes in the graph.
854 typedef typename Base::Graph::Node Node;
856 /// Pointer to the underlying graph.
858 ///Pointer to the map of reached nodes.
860 ///Pointer to the map of processed nodes.
862 ///Pointer to the map of predecessors edges.
864 ///Pointer to the map of distances.
866 ///Pointer to the source node.
872 /// This constructor does not require parameters, therefore it initiates
873 /// all of the attributes to default values (0, INVALID).
874 BfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0),
875 _dist(0), _source(INVALID) {}
879 /// This constructor requires some parameters,
880 /// listed in the parameters list.
881 /// Others are initiated to 0.
882 /// \param g is the initial value of \ref _g
883 /// \param s is the initial value of \ref _source
884 BfsWizardBase(const GR &g, Node s=INVALID) :
885 _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
886 _reached(0), _processed(0), _pred(0), _dist(0), _source(s) {}
890 /// A class to make the usage of Bfs algorithm easier
892 /// This class is created to make it easier to use Bfs algorithm.
893 /// It uses the functions and features of the plain \ref Bfs,
894 /// but it is much simpler to use it.
896 /// Simplicity means that the way to change the types defined
897 /// in the traits class is based on functions that returns the new class
898 /// and not on templatable built-in classes.
899 /// When using the plain \ref Bfs
900 /// the new class with the modified type comes from
901 /// the original class by using the ::
902 /// operator. In the case of \ref BfsWizard only
903 /// a function have to be called and it will
904 /// return the needed class.
906 /// It does not have own \ref run method. When its \ref run method is called
907 /// it initiates a plain \ref Bfs class, and calls the \ref Bfs::run
910 class BfsWizard : public TR
914 ///The type of the underlying graph.
915 typedef typename TR::Graph Graph;
917 typedef typename Graph::Node Node;
919 typedef typename Graph::NodeIt NodeIt;
921 typedef typename Graph::Edge Edge;
923 typedef typename Graph::OutEdgeIt OutEdgeIt;
925 ///\brief The type of the map that stores
927 typedef typename TR::ReachedMap ReachedMap;
928 ///\brief The type of the map that stores
929 ///the processed nodes
930 typedef typename TR::ProcessedMap ProcessedMap;
931 ///\brief The type of the map that stores the last
932 ///edges of the shortest paths.
933 typedef typename TR::PredMap PredMap;
934 ///The type of the map that stores the dists of the nodes.
935 typedef typename TR::DistMap DistMap;
939 BfsWizard() : TR() {}
941 /// Constructor that requires parameters.
943 /// Constructor that requires parameters.
944 /// These parameters will be the default values for the traits class.
945 BfsWizard(const Graph &g, Node s=INVALID) :
949 BfsWizard(const TR &b) : TR(b) {}
953 ///Runs Bfs algorithm from a given node.
955 ///Runs Bfs algorithm from a given node.
956 ///The node can be given by the \ref source function.
959 if(Base::_source==INVALID) throw UninitializedParameter();
960 Bfs<Graph,TR> alg(*reinterpret_cast<const Graph*>(Base::_g));
962 alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
964 alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
966 alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
968 alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
969 alg.run(Base::_source);
972 ///Runs Bfs algorithm from the given node.
974 ///Runs Bfs algorithm from the given node.
975 ///\param s is the given source.
983 struct DefPredMapBase : public Base {
985 static PredMap *createPredMap(const Graph &) { return 0; };
986 DefPredMapBase(const TR &b) : TR(b) {}
989 ///\brief \ref named-templ-param "Named parameter"
990 ///function for setting PredMap
992 /// \ref named-templ-param "Named parameter"
993 ///function for setting PredMap
996 BfsWizard<DefPredMapBase<T> > predMap(const T &t)
998 Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
999 return BfsWizard<DefPredMapBase<T> >(*this);
1004 struct DefReachedMapBase : public Base {
1005 typedef T ReachedMap;
1006 static ReachedMap *createReachedMap(const Graph &) { return 0; };
1007 DefReachedMapBase(const TR &b) : TR(b) {}
1010 ///\brief \ref named-templ-param "Named parameter"
1011 ///function for setting ReachedMap
1013 /// \ref named-templ-param "Named parameter"
1014 ///function for setting ReachedMap
1017 BfsWizard<DefReachedMapBase<T> > reachedMap(const T &t)
1019 Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1020 return BfsWizard<DefReachedMapBase<T> >(*this);
1025 struct DefProcessedMapBase : public Base {
1026 typedef T ProcessedMap;
1027 static ProcessedMap *createProcessedMap(const Graph &) { return 0; };
1028 DefProcessedMapBase(const TR &b) : TR(b) {}
1031 ///\brief \ref named-templ-param "Named parameter"
1032 ///function for setting ProcessedMap
1034 /// \ref named-templ-param "Named parameter"
1035 ///function for setting ProcessedMap
1038 BfsWizard<DefProcessedMapBase<T> > processedMap(const T &t)
1040 Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1041 return BfsWizard<DefProcessedMapBase<T> >(*this);
1046 struct DefDistMapBase : public Base {
1048 static DistMap *createDistMap(const Graph &) { return 0; };
1049 DefDistMapBase(const TR &b) : TR(b) {}
1052 ///\brief \ref named-templ-param "Named parameter"
1053 ///function for setting DistMap type
1055 /// \ref named-templ-param "Named parameter"
1056 ///function for setting DistMap type
1059 BfsWizard<DefDistMapBase<T> > distMap(const T &t)
1061 Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1062 return BfsWizard<DefDistMapBase<T> >(*this);
1065 /// Sets the source node, from which the Bfs algorithm runs.
1067 /// Sets the source node, from which the Bfs algorithm runs.
1068 /// \param s is the source node.
1069 BfsWizard<TR> &source(Node s)
1077 ///Function type interface for Bfs algorithm.
1080 ///Function type interface for Bfs algorithm.
1082 ///This function also has several
1083 ///\ref named-templ-func-param "named parameters",
1084 ///they are declared as the members of class \ref BfsWizard.
1086 ///example shows how to use these parameters.
1088 /// bfs(g,source).predMap(preds).run();
1090 ///\warning Don't forget to put the \ref BfsWizard::run() "run()"
1091 ///to the end of the parameter list.
1095 BfsWizard<BfsWizardBase<GR> >
1096 bfs(const GR &g,typename GR::Node s=INVALID)
1098 return BfsWizard<BfsWizardBase<GR> >(g,s);
1102 /// \brief Visitor class for bfs.
1104 /// It gives a simple interface for a functional interface for bfs
1105 /// traversal. The traversal on a linear data structure.
1106 template <typename _Graph>
1108 typedef _Graph Graph;
1109 typedef typename Graph::Edge Edge;
1110 typedef typename Graph::Node Node;
1111 /// \brief Called when the edge reach a node.
1113 /// It is called when the bfs find an edge which target is not
1115 void discover(const Edge& edge) {}
1116 /// \brief Called when the node reached first time.
1118 /// It is Called when the node reached first time.
1119 void reach(const Node& node) {}
1120 /// \brief Called when the edge examined but target of the edge
1121 /// already discovered.
1123 /// It called when the edge examined but the target of the edge
1124 /// already discovered.
1125 void examine(const Edge& edge) {}
1126 /// \brief Called for the source node of the bfs.
1128 /// It is called for the source node of the bfs.
1129 void start(const Node& node) {}
1130 /// \brief Called when the node processed.
1132 /// It is Called when the node processed.
1133 void process(const Node& node) {}
1136 template <typename _Graph>
1138 typedef _Graph Graph;
1139 typedef typename Graph::Edge Edge;
1140 typedef typename Graph::Node Node;
1141 void discover(const Edge&) {}
1142 void reach(const Node&) {}
1143 void examine(const Edge&) {}
1144 void start(const Node&) {}
1145 void process(const Node&) {}
1147 template <typename _Visitor>
1148 struct Constraints {
1149 void constraints() {
1152 visitor.discover(edge);
1153 visitor.reach(node);
1154 visitor.examine(edge);
1155 visitor.start(node);
1156 visitor.process(node);
1163 /// \brief Default traits class of BfsVisit class.
1165 /// Default traits class of BfsVisit class.
1166 /// \param _Graph Graph type.
1167 template<class _Graph>
1168 struct BfsVisitDefaultTraits {
1170 /// \brief The graph type the algorithm runs on.
1171 typedef _Graph Graph;
1173 /// \brief The type of the map that indicates which nodes are reached.
1175 /// The type of the map that indicates which nodes are reached.
1176 /// It must meet the \ref concepts::WriteMap "WriteMap" concept.
1177 /// \todo named parameter to set this type, function to read and write.
1178 typedef typename Graph::template NodeMap<bool> ReachedMap;
1180 /// \brief Instantiates a ReachedMap.
1182 /// This function instantiates a \ref ReachedMap.
1183 /// \param graph is the graph, to which
1184 /// we would like to define the \ref ReachedMap.
1185 static ReachedMap *createReachedMap(const Graph &graph) {
1186 return new ReachedMap(graph);
1191 /// %BFS Visit algorithm class.
1194 /// This class provides an efficient implementation of the %BFS algorithm
1195 /// with visitor interface.
1197 /// The %BfsVisit class provides an alternative interface to the Bfs
1198 /// class. It works with callback mechanism, the BfsVisit object calls
1199 /// on every bfs event the \c Visitor class member functions.
1201 /// \param _Graph The graph type the algorithm runs on. The default value is
1202 /// \ref ListGraph. The value of _Graph is not used directly by Bfs, it
1203 /// is only passed to \ref BfsDefaultTraits.
1204 /// \param _Visitor The Visitor object for the algorithm. The
1205 /// \ref BfsVisitor "BfsVisitor<_Graph>" is an empty Visitor which
1206 /// does not observe the Bfs events. If you want to observe the bfs
1207 /// events you should implement your own Visitor class.
1208 /// \param _Traits Traits class to set various data types used by the
1209 /// algorithm. The default traits class is
1210 /// \ref BfsVisitDefaultTraits "BfsVisitDefaultTraits<_Graph>".
1211 /// See \ref BfsVisitDefaultTraits for the documentation of
1212 /// a Bfs visit traits class.
1214 /// \author Jacint Szabo, Alpar Juttner and Balazs Dezso
1216 template <typename _Graph, typename _Visitor, typename _Traits>
1218 template <typename _Graph = ListGraph,
1219 typename _Visitor = BfsVisitor<_Graph>,
1220 typename _Traits = BfsDefaultTraits<_Graph> >
1225 /// \brief \ref Exception for uninitialized parameters.
1227 /// This error represents problems in the initialization
1228 /// of the parameters of the algorithms.
1229 class UninitializedParameter : public lemon::UninitializedParameter {
1231 virtual const char* what() const throw()
1233 return "lemon::BfsVisit::UninitializedParameter";
1237 typedef _Traits Traits;
1239 typedef typename Traits::Graph Graph;
1241 typedef _Visitor Visitor;
1243 ///The type of the map indicating which nodes are reached.
1244 typedef typename Traits::ReachedMap ReachedMap;
1248 typedef typename Graph::Node Node;
1249 typedef typename Graph::NodeIt NodeIt;
1250 typedef typename Graph::Edge Edge;
1251 typedef typename Graph::OutEdgeIt OutEdgeIt;
1253 /// Pointer to the underlying graph.
1254 const Graph *_graph;
1255 /// Pointer to the visitor object.
1257 ///Pointer to the map of reached status of the nodes.
1258 ReachedMap *_reached;
1259 ///Indicates if \ref _reached is locally allocated (\c true) or not.
1262 std::vector<typename Graph::Node> _list;
1263 int _list_front, _list_back;
1265 /// \brief Creates the maps if necessary.
1267 /// Creates the maps if necessary.
1268 void create_maps() {
1270 local_reached = true;
1271 _reached = Traits::createReachedMap(*_graph);
1281 typedef BfsVisit Create;
1283 /// \name Named template parameters
1287 struct DefReachedMapTraits : public Traits {
1288 typedef T ReachedMap;
1289 static ReachedMap *createReachedMap(const Graph &graph) {
1290 throw UninitializedParameter();
1293 /// \brief \ref named-templ-param "Named parameter" for setting
1296 /// \ref named-templ-param "Named parameter" for setting ReachedMap type
1298 struct DefReachedMap : public BfsVisit< Graph, Visitor,
1299 DefReachedMapTraits<T> > {
1300 typedef BfsVisit< Graph, Visitor, DefReachedMapTraits<T> > Create;
1306 /// \brief Constructor.
1310 /// \param graph the graph the algorithm will run on.
1311 /// \param visitor The visitor of the algorithm.
1313 BfsVisit(const Graph& graph, Visitor& visitor)
1314 : _graph(&graph), _visitor(&visitor),
1315 _reached(0), local_reached(false) {}
1317 /// \brief Destructor.
1321 if(local_reached) delete _reached;
1324 /// \brief Sets the map indicating if a node is reached.
1326 /// Sets the map indicating if a node is reached.
1327 /// If you don't use this function before calling \ref run(),
1328 /// it will allocate one. The destuctor deallocates this
1329 /// automatically allocated map, of course.
1330 /// \return <tt> (*this) </tt>
1331 BfsVisit &reachedMap(ReachedMap &m) {
1334 local_reached = false;
1341 /// \name Execution control
1342 /// The simplest way to execute the algorithm is to use
1343 /// one of the member functions called \c run(...).
1345 /// If you need more control on the execution,
1346 /// first you must call \ref init(), then you can adda source node
1347 /// with \ref addSource().
1348 /// Finally \ref start() will perform the actual path
1352 /// \brief Initializes the internal data structures.
1354 /// Initializes the internal data structures.
1358 _list.resize(countNodes(*_graph));
1359 _list_front = _list_back = -1;
1360 for (NodeIt u(*_graph) ; u != INVALID ; ++u) {
1361 _reached->set(u, false);
1365 /// \brief Adds a new source node.
1367 /// Adds a new source node to the set of nodes to be processed.
1368 void addSource(Node s) {
1369 if(!(*_reached)[s]) {
1370 _reached->set(s,true);
1373 _list[++_list_back] = s;
1377 /// \brief Processes the next node.
1379 /// Processes the next node.
1381 /// \return The processed node.
1383 /// \pre The queue must not be empty!
1384 Node processNextNode() {
1385 Node n = _list[++_list_front];
1386 _visitor->process(n);
1388 for (_graph->firstOut(e, n); e != INVALID; _graph->nextOut(e)) {
1389 Node m = _graph->target(e);
1390 if (!(*_reached)[m]) {
1391 _visitor->discover(e);
1393 _reached->set(m, true);
1394 _list[++_list_back] = m;
1396 _visitor->examine(e);
1402 /// \brief Processes the next node.
1404 /// Processes the next node. And checks that the given target node
1405 /// is reached. If the target node is reachable from the processed
1406 /// node then the reached parameter will be set true. The reached
1407 /// parameter should be initially false.
1409 /// \param target The target node.
1410 /// \retval reach Indicates that the target node is reached.
1411 /// \return The processed node.
1413 /// \warning The queue must not be empty!
1414 Node processNextNode(Node target, bool& reach) {
1415 Node n = _list[++_list_front];
1416 _visitor->process(n);
1418 for (_graph->firstOut(e, n); e != INVALID; _graph->nextOut(e)) {
1419 Node m = _graph->target(e);
1420 if (!(*_reached)[m]) {
1421 _visitor->discover(e);
1423 _reached->set(m, true);
1424 _list[++_list_back] = m;
1425 reach = reach || (target == m);
1427 _visitor->examine(e);
1433 /// \brief Processes the next node.
1435 /// Processes the next node. And checks that at least one of
1436 /// reached node has true value in the \c nm node map. If one node
1437 /// with true value is reachable from the processed node then the
1438 /// rnode parameter will be set to the first of such nodes.
1440 /// \param nm The node map of possible targets.
1441 /// \retval rnode The reached target node.
1442 /// \return The processed node.
1444 /// \warning The queue must not be empty!
1445 template <typename NM>
1446 Node processNextNode(const NM& nm, Node& rnode) {
1447 Node n = _list[++_list_front];
1448 _visitor->process(n);
1450 for (_graph->firstOut(e, n); e != INVALID; _graph->nextOut(e)) {
1451 Node m = _graph->target(e);
1452 if (!(*_reached)[m]) {
1453 _visitor->discover(e);
1455 _reached->set(m, true);
1456 _list[++_list_back] = m;
1457 if (nm[m] && rnode == INVALID) rnode = m;
1459 _visitor->examine(e);
1465 /// \brief Next node to be processed.
1467 /// Next node to be processed.
1469 /// \return The next node to be processed or INVALID if the stack is
1472 return _list_front != _list_back ? _list[_list_front + 1] : INVALID;
1475 /// \brief Returns \c false if there are nodes
1476 /// to be processed in the queue
1478 /// Returns \c false if there are nodes
1479 /// to be processed in the queue
1480 bool emptyQueue() { return _list_front == _list_back; }
1482 /// \brief Returns the number of the nodes to be processed.
1484 /// Returns the number of the nodes to be processed in the queue.
1485 int queueSize() { return _list_back - _list_front; }
1487 /// \brief Executes the algorithm.
1489 /// Executes the algorithm.
1491 /// \pre init() must be called and at least one node should be added
1492 /// with addSource() before using this function.
1494 while ( !emptyQueue() ) processNextNode();
1497 /// \brief Executes the algorithm until \c dest is reached.
1499 /// Executes the algorithm until \c dest is reached.
1501 /// \pre init() must be called and at least one node should be added
1502 /// with addSource() before using this function.
1503 void start(Node dest) {
1505 while ( !emptyQueue() && !reach ) processNextNode(dest, reach);
1508 /// \brief Executes the algorithm until a condition is met.
1510 /// Executes the algorithm until a condition is met.
1512 /// \pre init() must be called and at least one node should be added
1513 /// with addSource() before using this function.
1515 ///\param nm must be a bool (or convertible) node map. The
1516 ///algorithm will stop when it reaches a node \c v with
1517 /// <tt>nm[v]</tt> true.
1519 ///\return The reached node \c v with <tt>nm[v]</tt> true or
1520 ///\c INVALID if no such node was found.
1521 template <typename NM>
1522 Node start(const NM &nm) {
1523 Node rnode = INVALID;
1524 while ( !emptyQueue() && rnode == INVALID ) {
1525 processNextNode(nm, rnode);
1530 /// \brief Runs %BFSVisit algorithm from node \c s.
1532 /// This method runs the %BFS algorithm from a root node \c s.
1533 /// \note b.run(s) is just a shortcut of the following code.
1545 /// \brief Runs %BFSVisit algorithm to visit all nodes in the graph.
1547 /// This method runs the %BFS algorithm in order to
1548 /// compute the %BFS path to each node. The algorithm computes
1549 /// - The %BFS tree.
1550 /// - The distance of each node from the root in the %BFS tree.
1552 ///\note b.run() is just a shortcut of the following code.
1555 /// for (NodeIt it(graph); it != INVALID; ++it) {
1556 /// if (!b.reached(it)) {
1557 /// b.addSource(it);
1564 for (NodeIt it(*_graph); it != INVALID; ++it) {
1573 /// \name Query Functions
1574 /// The result of the %BFS algorithm can be obtained using these
1576 /// Before the use of these functions,
1577 /// either run() or start() must be called.
1580 /// \brief Checks if a node is reachable from the root.
1582 /// Returns \c true if \c v is reachable from the root(s).
1583 /// \warning The source nodes are inditated as unreachable.
1584 /// \pre Either \ref run() or \ref start()
1585 /// must be called before using this function.
1587 bool reached(Node v) { return (*_reached)[v]; }
1591 } //END OF NAMESPACE LEMON