1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
3 * This file is a part of LEMON, a generic C++ optimization library.
5 * Copyright (C) 2003-2009
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 conform to the \ref concepts::WriteMap "WriteMap" concept.
51 typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
52 ///Instantiates a \c PredMap.
54 ///This function instantiates a \ref PredMap.
55 ///\param g is the digraph, to which we would like to define the
57 static PredMap *createPredMap(const Digraph &g)
59 return new PredMap(g);
62 ///The type of the map that indicates which nodes are processed.
64 ///The type of the map that indicates which nodes are processed.
65 ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
66 ///By default, it is a NullMap.
67 typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
68 ///Instantiates a \c ProcessedMap.
70 ///This function instantiates a \ref ProcessedMap.
71 ///\param g is the digraph, to which
72 ///we would like to define the \ref ProcessedMap
74 static ProcessedMap *createProcessedMap(const Digraph &g)
76 static ProcessedMap *createProcessedMap(const Digraph &)
79 return new ProcessedMap();
82 ///The type of the map that indicates which nodes are reached.
84 ///The type of the map that indicates which nodes are reached.
85 ///It must conform to the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
86 typedef typename Digraph::template NodeMap<bool> ReachedMap;
87 ///Instantiates a \c ReachedMap.
89 ///This function instantiates a \ref ReachedMap.
90 ///\param g is the digraph, to which
91 ///we would like to define the \ref ReachedMap.
92 static ReachedMap *createReachedMap(const Digraph &g)
94 return new ReachedMap(g);
97 ///The type of the map that stores the distances of the nodes.
99 ///The type of the map that stores the distances of the nodes.
100 ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
101 typedef typename Digraph::template NodeMap<int> DistMap;
102 ///Instantiates a \c DistMap.
104 ///This function instantiates a \ref DistMap.
105 ///\param g is the digraph, to which we would like to define the
107 static DistMap *createDistMap(const Digraph &g)
109 return new DistMap(g);
113 ///%BFS algorithm class.
116 ///This class provides an efficient implementation of the %BFS algorithm.
118 ///There is also a \ref bfs() "function-type interface" for the BFS
119 ///algorithm, which is convenient in the simplier cases and it can be
122 ///\tparam GR The type of the digraph the algorithm runs on.
123 ///The default type is \ref ListDigraph.
125 template <typename GR,
128 template <typename GR=ListDigraph,
129 typename TR=BfsDefaultTraits<GR> >
134 ///The type of the digraph the algorithm runs on.
135 typedef typename TR::Digraph Digraph;
137 ///\brief The type of the map that stores the predecessor arcs of the
139 typedef typename TR::PredMap PredMap;
140 ///The type of the map that stores the distances of the nodes.
141 typedef typename TR::DistMap DistMap;
142 ///The type of the map that indicates which nodes are reached.
143 typedef typename TR::ReachedMap ReachedMap;
144 ///The type of the map that indicates which nodes are processed.
145 typedef typename TR::ProcessedMap ProcessedMap;
146 ///The type of the paths.
147 typedef PredMapPath<Digraph, PredMap> Path;
149 ///The \ref BfsDefaultTraits "traits class" of the algorithm.
154 typedef typename Digraph::Node Node;
155 typedef typename Digraph::NodeIt NodeIt;
156 typedef typename Digraph::Arc Arc;
157 typedef typename Digraph::OutArcIt OutArcIt;
159 //Pointer to the underlying digraph.
161 //Pointer to the map of predecessor arcs.
163 //Indicates if _pred is locally allocated (true) or not.
165 //Pointer to the map of distances.
167 //Indicates if _dist is locally allocated (true) or not.
169 //Pointer to the map of reached status of the nodes.
170 ReachedMap *_reached;
171 //Indicates if _reached is locally allocated (true) or not.
173 //Pointer to the map of processed status of the nodes.
174 ProcessedMap *_processed;
175 //Indicates if _processed is locally allocated (true) or not.
176 bool local_processed;
178 std::vector<typename Digraph::Node> _queue;
179 int _queue_head,_queue_tail,_queue_next_dist;
182 //Creates the maps if necessary.
187 _pred = Traits::createPredMap(*G);
191 _dist = Traits::createDistMap(*G);
194 local_reached = true;
195 _reached = Traits::createReachedMap(*G);
198 local_processed = true;
199 _processed = Traits::createProcessedMap(*G);
211 ///\name Named Template Parameters
216 struct SetPredMapTraits : public Traits {
218 static PredMap *createPredMap(const Digraph &)
220 LEMON_ASSERT(false, "PredMap is not initialized");
221 return 0; // ignore warnings
224 ///\brief \ref named-templ-param "Named parameter" for setting
227 ///\ref named-templ-param "Named parameter" for setting
229 ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
231 struct SetPredMap : public Bfs< Digraph, SetPredMapTraits<T> > {
232 typedef Bfs< Digraph, SetPredMapTraits<T> > Create;
236 struct SetDistMapTraits : public Traits {
238 static DistMap *createDistMap(const Digraph &)
240 LEMON_ASSERT(false, "DistMap is not initialized");
241 return 0; // ignore warnings
244 ///\brief \ref named-templ-param "Named parameter" for setting
247 ///\ref named-templ-param "Named parameter" for setting
249 ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
251 struct SetDistMap : public Bfs< Digraph, SetDistMapTraits<T> > {
252 typedef Bfs< Digraph, SetDistMapTraits<T> > Create;
256 struct SetReachedMapTraits : public Traits {
257 typedef T ReachedMap;
258 static ReachedMap *createReachedMap(const Digraph &)
260 LEMON_ASSERT(false, "ReachedMap is not initialized");
261 return 0; // ignore warnings
264 ///\brief \ref named-templ-param "Named parameter" for setting
265 ///\c ReachedMap type.
267 ///\ref named-templ-param "Named parameter" for setting
268 ///\c ReachedMap type.
269 ///It must conform to the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
271 struct SetReachedMap : public Bfs< Digraph, SetReachedMapTraits<T> > {
272 typedef Bfs< Digraph, SetReachedMapTraits<T> > Create;
276 struct SetProcessedMapTraits : public Traits {
277 typedef T ProcessedMap;
278 static ProcessedMap *createProcessedMap(const Digraph &)
280 LEMON_ASSERT(false, "ProcessedMap is not initialized");
281 return 0; // ignore warnings
284 ///\brief \ref named-templ-param "Named parameter" for setting
285 ///\c ProcessedMap type.
287 ///\ref named-templ-param "Named parameter" for setting
288 ///\c ProcessedMap type.
289 ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
291 struct SetProcessedMap : public Bfs< Digraph, SetProcessedMapTraits<T> > {
292 typedef Bfs< Digraph, SetProcessedMapTraits<T> > Create;
295 struct SetStandardProcessedMapTraits : public Traits {
296 typedef typename Digraph::template NodeMap<bool> ProcessedMap;
297 static ProcessedMap *createProcessedMap(const Digraph &g)
299 return new ProcessedMap(g);
300 return 0; // ignore warnings
303 ///\brief \ref named-templ-param "Named parameter" for setting
304 ///\c ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
306 ///\ref named-templ-param "Named parameter" for setting
307 ///\c ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
308 ///If you don't set it explicitly, it will be automatically allocated.
309 struct SetStandardProcessedMap :
310 public Bfs< Digraph, SetStandardProcessedMapTraits > {
311 typedef Bfs< Digraph, SetStandardProcessedMapTraits > Create;
321 ///\param g The digraph the algorithm runs on.
322 Bfs(const Digraph &g) :
324 _pred(NULL), local_pred(false),
325 _dist(NULL), local_dist(false),
326 _reached(NULL), local_reached(false),
327 _processed(NULL), local_processed(false)
333 if(local_pred) delete _pred;
334 if(local_dist) delete _dist;
335 if(local_reached) delete _reached;
336 if(local_processed) delete _processed;
339 ///Sets the map that stores the predecessor arcs.
341 ///Sets the map that stores the predecessor arcs.
342 ///If you don't use this function before calling \ref run(Node) "run()"
343 ///or \ref init(), an instance will be allocated automatically.
344 ///The destructor deallocates this automatically allocated map,
346 ///\return <tt> (*this) </tt>
347 Bfs &predMap(PredMap &m)
357 ///Sets the map that indicates which nodes are reached.
359 ///Sets the map that indicates which nodes are reached.
360 ///If you don't use this function before calling \ref run(Node) "run()"
361 ///or \ref init(), an instance will be allocated automatically.
362 ///The destructor deallocates this automatically allocated map,
364 ///\return <tt> (*this) </tt>
365 Bfs &reachedMap(ReachedMap &m)
375 ///Sets the map that indicates which nodes are processed.
377 ///Sets the map that indicates which nodes are processed.
378 ///If you don't use this function before calling \ref run(Node) "run()"
379 ///or \ref init(), an instance will be allocated automatically.
380 ///The destructor deallocates this automatically allocated map,
382 ///\return <tt> (*this) </tt>
383 Bfs &processedMap(ProcessedMap &m)
385 if(local_processed) {
387 local_processed=false;
393 ///Sets the map that stores the distances of the nodes.
395 ///Sets the map that stores the distances of the nodes calculated by
397 ///If you don't use this function before calling \ref run(Node) "run()"
398 ///or \ref init(), an instance will be allocated automatically.
399 ///The destructor deallocates this automatically allocated map,
401 ///\return <tt> (*this) </tt>
402 Bfs &distMap(DistMap &m)
414 ///\name Execution Control
415 ///The simplest way to execute the BFS algorithm is to use one of the
416 ///member functions called \ref run(Node) "run()".\n
417 ///If you need better control on the execution, you have to call
418 ///\ref init() first, then you can add several source nodes with
419 ///\ref addSource(). Finally the actual path computation can be
420 ///performed with one of the \ref start() functions.
424 ///\brief Initializes the internal data structures.
426 ///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 ///\pre 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(OutArcIt 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 if the given target node
485 ///is reached. If the target node is reachable from the processed
486 ///node, then the \c reach parameter will be set to \c true.
488 ///\param target The target node.
489 ///\retval reach Indicates if the target node is reached.
490 ///It should be initially \c false.
492 ///\return The processed node.
494 ///\pre 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(OutArcIt 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 if at least one of reached
518 ///nodes has \c true value in the \c nm node map. If one node
519 ///with \c true value is reachable from the processed node, then the
520 ///\c rnode parameter will be set to the first of such nodes.
522 ///\param nm A \c bool (or convertible) node map that indicates the
524 ///\retval rnode The reached target node.
525 ///It should be initially \c INVALID.
527 ///\return The processed node.
529 ///\pre The queue must not be empty.
531 Node processNextNode(const NM& nm, Node& rnode)
533 if(_queue_tail==_queue_next_dist) {
535 _queue_next_dist=_queue_head;
537 Node n=_queue[_queue_tail++];
538 _processed->set(n,true);
540 for(OutArcIt e(*G,n);e!=INVALID;++e)
541 if(!(*_reached)[m=G->target(e)]) {
542 _queue[_queue_head++]=m;
543 _reached->set(m,true);
545 _dist->set(m,_curr_dist);
546 if (nm[m] && rnode == INVALID) rnode = m;
551 ///The next node to be processed.
553 ///Returns the next node to be processed or \c INVALID if the queue
555 Node nextNode() const
557 return _queue_tail<_queue_head?_queue[_queue_tail]:INVALID;
560 ///Returns \c false if there are nodes to be processed.
562 ///Returns \c false if there are nodes to be processed
564 bool emptyQueue() const { return _queue_tail==_queue_head; }
566 ///Returns the number of the nodes to be processed.
568 ///Returns the number of the nodes to be processed
570 int queueSize() const { return _queue_head-_queue_tail; }
572 ///Executes the algorithm.
574 ///Executes the algorithm.
576 ///This method runs the %BFS algorithm from the root node(s)
577 ///in order to compute the shortest path to each node.
579 ///The algorithm computes
580 ///- the shortest path tree (forest),
581 ///- the distance of each node from the root(s).
583 ///\pre init() must be called and at least one root node should be
584 ///added with addSource() before using this function.
586 ///\note <tt>b.start()</tt> is just a shortcut of the following code.
588 /// while ( !b.emptyQueue() ) {
589 /// b.processNextNode();
594 while ( !emptyQueue() ) processNextNode();
597 ///Executes the algorithm until the given target node is reached.
599 ///Executes the algorithm until the given target node is reached.
601 ///This method runs the %BFS algorithm from the root node(s)
602 ///in order to compute the shortest path to \c t.
604 ///The algorithm computes
605 ///- the shortest path to \c t,
606 ///- the distance of \c t from the root(s).
608 ///\pre init() must be called and at least one root node should be
609 ///added with addSource() before using this function.
611 ///\note <tt>b.start(t)</tt> is just a shortcut of the following code.
613 /// bool reach = false;
614 /// while ( !b.emptyQueue() && !reach ) {
615 /// b.processNextNode(t, reach);
621 while ( !emptyQueue() && !reach ) processNextNode(t, reach);
624 ///Executes the algorithm until a condition is met.
626 ///Executes the algorithm until a condition is met.
628 ///This method runs the %BFS algorithm from the root node(s) in
629 ///order to compute the shortest path to a node \c v with
630 /// <tt>nm[v]</tt> true, if such a node can be found.
632 ///\param nm A \c bool (or convertible) node map. The algorithm
633 ///will stop when it reaches a node \c v with <tt>nm[v]</tt> true.
635 ///\return The reached node \c v with <tt>nm[v]</tt> true or
636 ///\c INVALID if no such node was found.
638 ///\pre init() must be called and at least one root node should be
639 ///added with addSource() before using this function.
641 ///\note <tt>b.start(nm)</tt> is just a shortcut of the following code.
643 /// Node rnode = INVALID;
644 /// while ( !b.emptyQueue() && rnode == INVALID ) {
645 /// b.processNextNode(nm, rnode);
649 template<class NodeBoolMap>
650 Node start(const NodeBoolMap &nm)
652 Node rnode = INVALID;
653 while ( !emptyQueue() && rnode == INVALID ) {
654 processNextNode(nm, rnode);
659 ///Runs the algorithm from the given source node.
661 ///This method runs the %BFS algorithm from node \c s
662 ///in order to compute the shortest path to each node.
664 ///The algorithm computes
665 ///- the shortest path tree,
666 ///- the distance of each node from the root.
668 ///\note <tt>b.run(s)</tt> is just a shortcut of the following code.
680 ///Finds the shortest path between \c s and \c t.
682 ///This method runs the %BFS algorithm from node \c s
683 ///in order to compute the shortest path to node \c t
684 ///(it stops searching when \c t is processed).
686 ///\return \c true if \c t is reachable form \c s.
688 ///\note Apart from the return value, <tt>b.run(s,t)</tt> is just a
689 ///shortcut of the following code.
695 bool run(Node s,Node t) {
702 ///Runs the algorithm to visit all nodes in the digraph.
704 ///This method runs the %BFS algorithm in order to visit all nodes
707 ///\note <tt>b.run(s)</tt> is just a shortcut of the following code.
710 /// for (NodeIt n(gr); n != INVALID; ++n) {
711 /// if (!b.reached(n)) {
719 for (NodeIt n(*G); n != INVALID; ++n) {
729 ///\name Query Functions
730 ///The results of the BFS algorithm can be obtained using these
732 ///Either \ref run(Node) "run()" or \ref start() should be called
733 ///before using them.
737 ///The shortest path to the given node.
739 ///Returns the shortest path to the given node from the root(s).
741 ///\warning \c t should be reached from the root(s).
743 ///\pre Either \ref run(Node) "run()" or \ref init()
744 ///must be called before using this function.
745 Path path(Node t) const { return Path(*G, *_pred, t); }
747 ///The distance of the given node from the root(s).
749 ///Returns the distance of the given node from the root(s).
751 ///\warning If node \c v is not reached from the root(s), then
752 ///the return value of this function is undefined.
754 ///\pre Either \ref run(Node) "run()" or \ref init()
755 ///must be called before using this function.
756 int dist(Node v) const { return (*_dist)[v]; }
758 ///\brief Returns the 'previous arc' of the shortest path tree for
761 ///This function returns the 'previous arc' of the shortest path
762 ///tree for the node \c v, i.e. it returns the last arc of a
763 ///shortest path from a root to \c v. It is \c INVALID if \c v
764 ///is not reached from the root(s) or if \c v is a root.
766 ///The shortest path tree used here is equal to the shortest path
767 ///tree used in \ref predNode() and \ref predMap().
769 ///\pre Either \ref run(Node) "run()" or \ref init()
770 ///must be called before using this function.
771 Arc predArc(Node v) const { return (*_pred)[v];}
773 ///\brief Returns the 'previous node' of the shortest path tree for
776 ///This function returns the 'previous node' of the shortest path
777 ///tree for the node \c v, i.e. it returns the last but one node
778 ///of a shortest path from a root to \c v. It is \c INVALID
779 ///if \c v is not reached from the root(s) or if \c v is a root.
781 ///The shortest path tree used here is equal to the shortest path
782 ///tree used in \ref predArc() and \ref predMap().
784 ///\pre Either \ref run(Node) "run()" or \ref init()
785 ///must be called before using this function.
786 Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
787 G->source((*_pred)[v]); }
789 ///\brief Returns a const reference to the node map that stores the
790 /// distances of the nodes.
792 ///Returns a const reference to the node map that stores the distances
793 ///of the nodes calculated by the algorithm.
795 ///\pre Either \ref run(Node) "run()" or \ref init()
796 ///must be called before using this function.
797 const DistMap &distMap() const { return *_dist;}
799 ///\brief Returns a const reference to the node map that stores the
802 ///Returns a const reference to the node map that stores the predecessor
803 ///arcs, which form the shortest path tree (forest).
805 ///\pre Either \ref run(Node) "run()" or \ref init()
806 ///must be called before using this function.
807 const PredMap &predMap() const { return *_pred;}
809 ///Checks if the given node is reached from the root(s).
811 ///Returns \c true if \c v is reached from the root(s).
813 ///\pre Either \ref run(Node) "run()" or \ref init()
814 ///must be called before using this function.
815 bool reached(Node v) const { return (*_reached)[v]; }
820 ///Default traits class of bfs() function.
822 ///Default traits class of bfs() function.
823 ///\tparam GR Digraph type.
825 struct BfsWizardDefaultTraits
827 ///The type of the digraph the algorithm runs on.
830 ///\brief The type of the map that stores the predecessor
831 ///arcs of the shortest paths.
833 ///The type of the map that stores the predecessor
834 ///arcs of the shortest paths.
835 ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
836 typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
837 ///Instantiates a PredMap.
839 ///This function instantiates a PredMap.
840 ///\param g is the digraph, to which we would like to define the
842 static PredMap *createPredMap(const Digraph &g)
844 return new PredMap(g);
847 ///The type of the map that indicates which nodes are processed.
849 ///The type of the map that indicates which nodes are processed.
850 ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
851 ///By default, it is a NullMap.
852 typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
853 ///Instantiates a ProcessedMap.
855 ///This function instantiates a ProcessedMap.
856 ///\param g is the digraph, to which
857 ///we would like to define the ProcessedMap.
859 static ProcessedMap *createProcessedMap(const Digraph &g)
861 static ProcessedMap *createProcessedMap(const Digraph &)
864 return new ProcessedMap();
867 ///The type of the map that indicates which nodes are reached.
869 ///The type of the map that indicates which nodes are reached.
870 ///It must conform to the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
871 typedef typename Digraph::template NodeMap<bool> ReachedMap;
872 ///Instantiates a ReachedMap.
874 ///This function instantiates a ReachedMap.
875 ///\param g is the digraph, to which
876 ///we would like to define the ReachedMap.
877 static ReachedMap *createReachedMap(const Digraph &g)
879 return new ReachedMap(g);
882 ///The type of the map that stores the distances of the nodes.
884 ///The type of the map that stores the distances of the nodes.
885 ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
886 typedef typename Digraph::template NodeMap<int> DistMap;
887 ///Instantiates a DistMap.
889 ///This function instantiates a DistMap.
890 ///\param g is the digraph, to which we would like to define
892 static DistMap *createDistMap(const Digraph &g)
894 return new DistMap(g);
897 ///The type of the shortest paths.
899 ///The type of the shortest paths.
900 ///It must conform to the \ref concepts::Path "Path" concept.
901 typedef lemon::Path<Digraph> Path;
904 /// Default traits class used by BfsWizard
906 /// Default traits class used by BfsWizard.
907 /// \tparam GR The type of the digraph.
909 class BfsWizardBase : public BfsWizardDefaultTraits<GR>
912 typedef BfsWizardDefaultTraits<GR> Base;
914 //The type of the nodes in the digraph.
915 typedef typename Base::Digraph::Node Node;
917 //Pointer to the digraph the algorithm runs on.
919 //Pointer to the map of reached nodes.
921 //Pointer to the map of processed nodes.
923 //Pointer to the map of predecessors arcs.
925 //Pointer to the map of distances.
927 //Pointer to the shortest path to the target node.
929 //Pointer to the distance of the target node.
935 /// This constructor does not require parameters, it initiates
936 /// all of the attributes to \c 0.
937 BfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0),
938 _dist(0), _path(0), _di(0) {}
942 /// This constructor requires one parameter,
943 /// others are initiated to \c 0.
944 /// \param g The digraph the algorithm runs on.
945 BfsWizardBase(const GR &g) :
946 _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
947 _reached(0), _processed(0), _pred(0), _dist(0), _path(0), _di(0) {}
951 /// Auxiliary class for the function-type interface of BFS algorithm.
953 /// This auxiliary class is created to implement the
954 /// \ref bfs() "function-type interface" of \ref Bfs algorithm.
955 /// It does not have own \ref run(Node) "run()" method, it uses the
956 /// functions and features of the plain \ref Bfs.
958 /// This class should only be used through the \ref bfs() function,
959 /// which makes it easier to use the algorithm.
961 class BfsWizard : public TR
965 typedef typename TR::Digraph Digraph;
967 typedef typename Digraph::Node Node;
968 typedef typename Digraph::NodeIt NodeIt;
969 typedef typename Digraph::Arc Arc;
970 typedef typename Digraph::OutArcIt OutArcIt;
972 typedef typename TR::PredMap PredMap;
973 typedef typename TR::DistMap DistMap;
974 typedef typename TR::ReachedMap ReachedMap;
975 typedef typename TR::ProcessedMap ProcessedMap;
976 typedef typename TR::Path Path;
981 BfsWizard() : TR() {}
983 /// Constructor that requires parameters.
985 /// Constructor that requires parameters.
986 /// These parameters will be the default values for the traits class.
987 /// \param g The digraph the algorithm runs on.
988 BfsWizard(const Digraph &g) :
992 BfsWizard(const TR &b) : TR(b) {}
996 ///Runs BFS algorithm from the given source node.
998 ///This method runs BFS algorithm from node \c s
999 ///in order to compute the shortest path to each node.
1002 Bfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
1004 alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1006 alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1008 alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
1009 if (Base::_processed)
1010 alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1017 ///Finds the shortest path between \c s and \c t.
1019 ///This method runs BFS algorithm from node \c s
1020 ///in order to compute the shortest path to node \c t
1021 ///(it stops searching when \c t is processed).
1023 ///\return \c true if \c t is reachable form \c s.
1024 bool run(Node s, Node t)
1026 Bfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
1028 alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1030 alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1032 alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
1033 if (Base::_processed)
1034 alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1037 *reinterpret_cast<Path*>(Base::_path) = alg.path(t);
1039 *Base::_di = alg.dist(t);
1040 return alg.reached(t);
1043 ///Runs BFS algorithm to visit all nodes in the digraph.
1045 ///This method runs BFS algorithm in order to visit all nodes
1053 struct SetPredMapBase : public Base {
1055 static PredMap *createPredMap(const Digraph &) { return 0; };
1056 SetPredMapBase(const TR &b) : TR(b) {}
1059 ///\brief \ref named-templ-param "Named parameter" for setting
1060 ///the predecessor map.
1062 ///\ref named-templ-param "Named parameter" function for setting
1063 ///the map that stores the predecessor arcs of the nodes.
1065 BfsWizard<SetPredMapBase<T> > predMap(const T &t)
1067 Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1068 return BfsWizard<SetPredMapBase<T> >(*this);
1072 struct SetReachedMapBase : public Base {
1073 typedef T ReachedMap;
1074 static ReachedMap *createReachedMap(const Digraph &) { return 0; };
1075 SetReachedMapBase(const TR &b) : TR(b) {}
1078 ///\brief \ref named-templ-param "Named parameter" for setting
1081 ///\ref named-templ-param "Named parameter" function for setting
1082 ///the map that indicates which nodes are reached.
1084 BfsWizard<SetReachedMapBase<T> > reachedMap(const T &t)
1086 Base::_reached=reinterpret_cast<void*>(const_cast<T*>(&t));
1087 return BfsWizard<SetReachedMapBase<T> >(*this);
1091 struct SetDistMapBase : public Base {
1093 static DistMap *createDistMap(const Digraph &) { return 0; };
1094 SetDistMapBase(const TR &b) : TR(b) {}
1097 ///\brief \ref named-templ-param "Named parameter" for setting
1098 ///the distance map.
1100 ///\ref named-templ-param "Named parameter" function for setting
1101 ///the map that stores the distances of the nodes calculated
1102 ///by the algorithm.
1104 BfsWizard<SetDistMapBase<T> > distMap(const T &t)
1106 Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1107 return BfsWizard<SetDistMapBase<T> >(*this);
1111 struct SetProcessedMapBase : public Base {
1112 typedef T ProcessedMap;
1113 static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
1114 SetProcessedMapBase(const TR &b) : TR(b) {}
1117 ///\brief \ref named-func-param "Named parameter" for setting
1118 ///the processed map.
1120 ///\ref named-templ-param "Named parameter" function for setting
1121 ///the map that indicates which nodes are processed.
1123 BfsWizard<SetProcessedMapBase<T> > processedMap(const T &t)
1125 Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1126 return BfsWizard<SetProcessedMapBase<T> >(*this);
1130 struct SetPathBase : public Base {
1132 SetPathBase(const TR &b) : TR(b) {}
1134 ///\brief \ref named-func-param "Named parameter"
1135 ///for getting the shortest path to the target node.
1137 ///\ref named-func-param "Named parameter"
1138 ///for getting the shortest path to the target node.
1140 BfsWizard<SetPathBase<T> > path(const T &t)
1142 Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t));
1143 return BfsWizard<SetPathBase<T> >(*this);
1146 ///\brief \ref named-func-param "Named parameter"
1147 ///for getting the distance of the target node.
1149 ///\ref named-func-param "Named parameter"
1150 ///for getting the distance of the target node.
1151 BfsWizard dist(const int &d)
1153 Base::_di=const_cast<int*>(&d);
1159 ///Function-type interface for BFS algorithm.
1162 ///Function-type interface for BFS algorithm.
1164 ///This function also has several \ref named-func-param "named parameters",
1165 ///they are declared as the members of class \ref BfsWizard.
1166 ///The following examples show how to use these parameters.
1168 /// // Compute shortest path from node s to each node
1169 /// bfs(g).predMap(preds).distMap(dists).run(s);
1171 /// // Compute shortest path from s to t
1172 /// bool reached = bfs(g).path(p).dist(d).run(s,t);
1174 ///\warning Don't forget to put the \ref BfsWizard::run(Node) "run()"
1175 ///to the end of the parameter list.
1179 BfsWizard<BfsWizardBase<GR> >
1180 bfs(const GR &digraph)
1182 return BfsWizard<BfsWizardBase<GR> >(digraph);
1186 /// \brief Visitor class for BFS.
1188 /// This class defines the interface of the BfsVisit events, and
1189 /// it could be the base of a real visitor class.
1190 template <typename GR>
1193 typedef typename Digraph::Arc Arc;
1194 typedef typename Digraph::Node Node;
1195 /// \brief Called for the source node(s) of the BFS.
1197 /// This function is called for the source node(s) of the BFS.
1198 void start(const Node& node) {}
1199 /// \brief Called when a node is reached first time.
1201 /// This function is called when a node is reached first time.
1202 void reach(const Node& node) {}
1203 /// \brief Called when a node is processed.
1205 /// This function is called when a node is processed.
1206 void process(const Node& node) {}
1207 /// \brief Called when an arc reaches a new node.
1209 /// This function is called when the BFS finds an arc whose target node
1210 /// is not reached yet.
1211 void discover(const Arc& arc) {}
1212 /// \brief Called when an arc is examined but its target node is
1213 /// already discovered.
1215 /// This function is called when an arc is examined but its target node is
1216 /// already discovered.
1217 void examine(const Arc& arc) {}
1220 template <typename GR>
1223 typedef typename Digraph::Arc Arc;
1224 typedef typename Digraph::Node Node;
1225 void start(const Node&) {}
1226 void reach(const Node&) {}
1227 void process(const Node&) {}
1228 void discover(const Arc&) {}
1229 void examine(const Arc&) {}
1231 template <typename _Visitor>
1232 struct Constraints {
1233 void constraints() {
1236 visitor.start(node);
1237 visitor.reach(node);
1238 visitor.process(node);
1239 visitor.discover(arc);
1240 visitor.examine(arc);
1247 /// \brief Default traits class of BfsVisit class.
1249 /// Default traits class of BfsVisit class.
1250 /// \tparam GR The type of the digraph the algorithm runs on.
1252 struct BfsVisitDefaultTraits {
1254 /// \brief The type of the digraph the algorithm runs on.
1257 /// \brief The type of the map that indicates which nodes are reached.
1259 /// The type of the map that indicates which nodes are reached.
1260 /// It must conform to the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
1261 typedef typename Digraph::template NodeMap<bool> ReachedMap;
1263 /// \brief Instantiates a ReachedMap.
1265 /// This function instantiates a ReachedMap.
1266 /// \param digraph is the digraph, to which
1267 /// we would like to define the ReachedMap.
1268 static ReachedMap *createReachedMap(const Digraph &digraph) {
1269 return new ReachedMap(digraph);
1276 /// \brief BFS algorithm class with visitor interface.
1278 /// This class provides an efficient implementation of the BFS algorithm
1279 /// with visitor interface.
1281 /// The BfsVisit class provides an alternative interface to the Bfs
1282 /// class. It works with callback mechanism, the BfsVisit object calls
1283 /// the member functions of the \c Visitor class on every BFS event.
1285 /// This interface of the BFS algorithm should be used in special cases
1286 /// when extra actions have to be performed in connection with certain
1287 /// events of the BFS algorithm. Otherwise consider to use Bfs or bfs()
1290 /// \tparam GR The type of the digraph the algorithm runs on.
1291 /// The default type is \ref ListDigraph.
1292 /// The value of GR is not used directly by \ref BfsVisit,
1293 /// it is only passed to \ref BfsVisitDefaultTraits.
1294 /// \tparam VS The Visitor type that is used by the algorithm.
1295 /// \ref BfsVisitor "BfsVisitor<GR>" is an empty visitor, which
1296 /// does not observe the BFS events. If you want to observe the BFS
1297 /// events, you should implement your own visitor class.
1298 /// \tparam TR Traits class to set various data types used by the
1299 /// algorithm. The default traits class is
1300 /// \ref BfsVisitDefaultTraits "BfsVisitDefaultTraits<GR>".
1301 /// See \ref BfsVisitDefaultTraits for the documentation of
1302 /// a BFS visit traits class.
1304 template <typename GR, typename VS, typename TR>
1306 template <typename GR = ListDigraph,
1307 typename VS = BfsVisitor<GR>,
1308 typename TR = BfsVisitDefaultTraits<GR> >
1313 ///The traits class.
1316 ///The type of the digraph the algorithm runs on.
1317 typedef typename Traits::Digraph Digraph;
1319 ///The visitor type used by the algorithm.
1322 ///The type of the map that indicates which nodes are reached.
1323 typedef typename Traits::ReachedMap ReachedMap;
1327 typedef typename Digraph::Node Node;
1328 typedef typename Digraph::NodeIt NodeIt;
1329 typedef typename Digraph::Arc Arc;
1330 typedef typename Digraph::OutArcIt OutArcIt;
1332 //Pointer to the underlying digraph.
1333 const Digraph *_digraph;
1334 //Pointer to the visitor object.
1336 //Pointer to the map of reached status of the nodes.
1337 ReachedMap *_reached;
1338 //Indicates if _reached is locally allocated (true) or not.
1341 std::vector<typename Digraph::Node> _list;
1342 int _list_front, _list_back;
1344 //Creates the maps if necessary.
1345 void create_maps() {
1347 local_reached = true;
1348 _reached = Traits::createReachedMap(*_digraph);
1358 typedef BfsVisit Create;
1360 /// \name Named Template Parameters
1364 struct SetReachedMapTraits : public Traits {
1365 typedef T ReachedMap;
1366 static ReachedMap *createReachedMap(const Digraph &digraph) {
1367 LEMON_ASSERT(false, "ReachedMap is not initialized");
1368 return 0; // ignore warnings
1371 /// \brief \ref named-templ-param "Named parameter" for setting
1372 /// ReachedMap type.
1374 /// \ref named-templ-param "Named parameter" for setting ReachedMap type.
1376 struct SetReachedMap : public BfsVisit< Digraph, Visitor,
1377 SetReachedMapTraits<T> > {
1378 typedef BfsVisit< Digraph, Visitor, SetReachedMapTraits<T> > Create;
1384 /// \brief Constructor.
1388 /// \param digraph The digraph the algorithm runs on.
1389 /// \param visitor The visitor object of the algorithm.
1390 BfsVisit(const Digraph& digraph, Visitor& visitor)
1391 : _digraph(&digraph), _visitor(&visitor),
1392 _reached(0), local_reached(false) {}
1394 /// \brief Destructor.
1396 if(local_reached) delete _reached;
1399 /// \brief Sets the map that indicates which nodes are reached.
1401 /// Sets the map that indicates which nodes are reached.
1402 /// If you don't use this function before calling \ref run(Node) "run()"
1403 /// or \ref init(), an instance will be allocated automatically.
1404 /// The destructor deallocates this automatically allocated map,
1406 /// \return <tt> (*this) </tt>
1407 BfsVisit &reachedMap(ReachedMap &m) {
1410 local_reached = false;
1418 /// \name Execution Control
1419 /// The simplest way to execute the BFS algorithm is to use one of the
1420 /// member functions called \ref run(Node) "run()".\n
1421 /// If you need better control on the execution, you have to call
1422 /// \ref init() first, then you can add several source nodes with
1423 /// \ref addSource(). Finally the actual path computation can be
1424 /// performed with one of the \ref start() functions.
1428 /// \brief Initializes the internal data structures.
1430 /// Initializes the internal data structures.
1433 _list.resize(countNodes(*_digraph));
1434 _list_front = _list_back = -1;
1435 for (NodeIt u(*_digraph) ; u != INVALID ; ++u) {
1436 _reached->set(u, false);
1440 /// \brief Adds a new source node.
1442 /// Adds a new source node to the set of nodes to be processed.
1443 void addSource(Node s) {
1444 if(!(*_reached)[s]) {
1445 _reached->set(s,true);
1448 _list[++_list_back] = s;
1452 /// \brief Processes the next node.
1454 /// Processes the next node.
1456 /// \return The processed node.
1458 /// \pre The queue must not be empty.
1459 Node processNextNode() {
1460 Node n = _list[++_list_front];
1461 _visitor->process(n);
1463 for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1464 Node m = _digraph->target(e);
1465 if (!(*_reached)[m]) {
1466 _visitor->discover(e);
1468 _reached->set(m, true);
1469 _list[++_list_back] = m;
1471 _visitor->examine(e);
1477 /// \brief Processes the next node.
1479 /// Processes the next node and checks if the given target node
1480 /// is reached. If the target node is reachable from the processed
1481 /// node, then the \c reach parameter will be set to \c true.
1483 /// \param target The target node.
1484 /// \retval reach Indicates if the target node is reached.
1485 /// It should be initially \c false.
1487 /// \return The processed node.
1489 /// \pre The queue must not be empty.
1490 Node processNextNode(Node target, bool& reach) {
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;
1501 reach = reach || (target == m);
1503 _visitor->examine(e);
1509 /// \brief Processes the next node.
1511 /// Processes the next node and checks if at least one of reached
1512 /// nodes has \c true value in the \c nm node map. If one node
1513 /// with \c true value is reachable from the processed node, then the
1514 /// \c rnode parameter will be set to the first of such nodes.
1516 /// \param nm A \c bool (or convertible) node map that indicates the
1517 /// possible targets.
1518 /// \retval rnode The reached target node.
1519 /// It should be initially \c INVALID.
1521 /// \return The processed node.
1523 /// \pre The queue must not be empty.
1524 template <typename NM>
1525 Node processNextNode(const NM& nm, Node& rnode) {
1526 Node n = _list[++_list_front];
1527 _visitor->process(n);
1529 for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1530 Node m = _digraph->target(e);
1531 if (!(*_reached)[m]) {
1532 _visitor->discover(e);
1534 _reached->set(m, true);
1535 _list[++_list_back] = m;
1536 if (nm[m] && rnode == INVALID) rnode = m;
1538 _visitor->examine(e);
1544 /// \brief The next node to be processed.
1546 /// Returns the next node to be processed or \c INVALID if the queue
1548 Node nextNode() const {
1549 return _list_front != _list_back ? _list[_list_front + 1] : INVALID;
1552 /// \brief Returns \c false if there are nodes
1553 /// to be processed.
1555 /// Returns \c false if there are nodes
1556 /// to be processed in the queue.
1557 bool emptyQueue() const { return _list_front == _list_back; }
1559 /// \brief Returns the number of the nodes to be processed.
1561 /// Returns the number of the nodes to be processed in the queue.
1562 int queueSize() const { return _list_back - _list_front; }
1564 /// \brief Executes the algorithm.
1566 /// Executes the algorithm.
1568 /// This method runs the %BFS algorithm from the root node(s)
1569 /// in order to compute the shortest path to each node.
1571 /// The algorithm computes
1572 /// - the shortest path tree (forest),
1573 /// - the distance of each node from the root(s).
1575 /// \pre init() must be called and at least one root node should be added
1576 /// with addSource() before using this function.
1578 /// \note <tt>b.start()</tt> is just a shortcut of the following code.
1580 /// while ( !b.emptyQueue() ) {
1581 /// b.processNextNode();
1585 while ( !emptyQueue() ) processNextNode();
1588 /// \brief Executes the algorithm until the given target node is reached.
1590 /// Executes the algorithm until the given target node is reached.
1592 /// This method runs the %BFS algorithm from the root node(s)
1593 /// in order to compute the shortest path to \c t.
1595 /// The algorithm computes
1596 /// - the shortest path to \c t,
1597 /// - the distance of \c t from the root(s).
1599 /// \pre init() must be called and at least one root node should be
1600 /// added with addSource() before using this function.
1602 /// \note <tt>b.start(t)</tt> is just a shortcut of the following code.
1604 /// bool reach = false;
1605 /// while ( !b.emptyQueue() && !reach ) {
1606 /// b.processNextNode(t, reach);
1609 void start(Node t) {
1611 while ( !emptyQueue() && !reach ) processNextNode(t, reach);
1614 /// \brief Executes the algorithm until a condition is met.
1616 /// Executes the algorithm until a condition is met.
1618 /// This method runs the %BFS algorithm from the root node(s) in
1619 /// order to compute the shortest path to a node \c v with
1620 /// <tt>nm[v]</tt> true, if such a node can be found.
1622 /// \param nm must be a bool (or convertible) node map. The
1623 /// algorithm will stop when it reaches a node \c v with
1624 /// <tt>nm[v]</tt> true.
1626 /// \return The reached node \c v with <tt>nm[v]</tt> true or
1627 /// \c INVALID if no such node was found.
1629 /// \pre init() must be called and at least one root node should be
1630 /// added with addSource() before using this function.
1632 /// \note <tt>b.start(nm)</tt> is just a shortcut of the following code.
1634 /// Node rnode = INVALID;
1635 /// while ( !b.emptyQueue() && rnode == INVALID ) {
1636 /// b.processNextNode(nm, rnode);
1640 template <typename NM>
1641 Node start(const NM &nm) {
1642 Node rnode = INVALID;
1643 while ( !emptyQueue() && rnode == INVALID ) {
1644 processNextNode(nm, rnode);
1649 /// \brief Runs the algorithm from the given source node.
1651 /// This method runs the %BFS algorithm from node \c s
1652 /// in order to compute the shortest path to each node.
1654 /// The algorithm computes
1655 /// - the shortest path tree,
1656 /// - the distance of each node from the root.
1658 /// \note <tt>b.run(s)</tt> is just a shortcut of the following code.
1670 /// \brief Finds the shortest path between \c s and \c t.
1672 /// This method runs the %BFS algorithm from node \c s
1673 /// in order to compute the shortest path to node \c t
1674 /// (it stops searching when \c t is processed).
1676 /// \return \c true if \c t is reachable form \c s.
1678 /// \note Apart from the return value, <tt>b.run(s,t)</tt> is just a
1679 /// shortcut of the following code.
1685 bool run(Node s,Node t) {
1692 /// \brief Runs the algorithm to visit all nodes in the digraph.
1694 /// This method runs the %BFS algorithm in order to visit all nodes
1697 /// \note <tt>b.run(s)</tt> is just a shortcut of the following code.
1700 /// for (NodeIt n(gr); n != INVALID; ++n) {
1701 /// if (!b.reached(n)) {
1709 for (NodeIt it(*_digraph); it != INVALID; ++it) {
1719 /// \name Query Functions
1720 /// The results of the BFS algorithm can be obtained using these
1722 /// Either \ref run(Node) "run()" or \ref start() should be called
1723 /// before using them.
1727 /// \brief Checks if the given node is reached from the root(s).
1729 /// Returns \c true if \c v is reached from the root(s).
1731 /// \pre Either \ref run(Node) "run()" or \ref init()
1732 /// must be called before using this function.
1733 bool reached(Node v) const { return (*_reached)[v]; }
1739 } //END OF NAMESPACE LEMON