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
705 ///compute the shortest path to each node.
707 ///The algorithm computes
708 ///- the shortest path tree (forest),
709 ///- the distance of each node from the root(s).
711 ///\note <tt>b.run(s)</tt> is just a shortcut of the following code.
714 /// for (NodeIt n(gr); n != INVALID; ++n) {
715 /// if (!b.reached(n)) {
723 for (NodeIt n(*G); n != INVALID; ++n) {
733 ///\name Query Functions
734 ///The results of the BFS algorithm can be obtained using these
736 ///Either \ref run(Node) "run()" or \ref start() should be called
737 ///before using them.
741 ///The shortest path to the given node.
743 ///Returns the shortest path to the given node from the root(s).
745 ///\warning \c t should be reached from the root(s).
747 ///\pre Either \ref run(Node) "run()" or \ref init()
748 ///must be called before using this function.
749 Path path(Node t) const { return Path(*G, *_pred, t); }
751 ///The distance of the given node from the root(s).
753 ///Returns the distance of the given node from the root(s).
755 ///\warning If node \c v is not reached from the root(s), then
756 ///the return value of this function is undefined.
758 ///\pre Either \ref run(Node) "run()" or \ref init()
759 ///must be called before using this function.
760 int dist(Node v) const { return (*_dist)[v]; }
762 ///\brief Returns the 'previous arc' of the shortest path tree for
765 ///This function returns the 'previous arc' of the shortest path
766 ///tree for the node \c v, i.e. it returns the last arc of a
767 ///shortest path from a root to \c v. It is \c INVALID if \c v
768 ///is not reached from the root(s) or if \c v is a root.
770 ///The shortest path tree used here is equal to the shortest path
771 ///tree used in \ref predNode() and \ref predMap().
773 ///\pre Either \ref run(Node) "run()" or \ref init()
774 ///must be called before using this function.
775 Arc predArc(Node v) const { return (*_pred)[v];}
777 ///\brief Returns the 'previous node' of the shortest path tree for
780 ///This function returns the 'previous node' of the shortest path
781 ///tree for the node \c v, i.e. it returns the last but one node
782 ///of a shortest path from a root to \c v. It is \c INVALID
783 ///if \c v is not reached from the root(s) or if \c v is a root.
785 ///The shortest path tree used here is equal to the shortest path
786 ///tree used in \ref predArc() and \ref predMap().
788 ///\pre Either \ref run(Node) "run()" or \ref init()
789 ///must be called before using this function.
790 Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
791 G->source((*_pred)[v]); }
793 ///\brief Returns a const reference to the node map that stores the
794 /// distances of the nodes.
796 ///Returns a const reference to the node map that stores the distances
797 ///of the nodes calculated by the algorithm.
799 ///\pre Either \ref run(Node) "run()" or \ref init()
800 ///must be called before using this function.
801 const DistMap &distMap() const { return *_dist;}
803 ///\brief Returns a const reference to the node map that stores the
806 ///Returns a const reference to the node map that stores the predecessor
807 ///arcs, which form the shortest path tree (forest).
809 ///\pre Either \ref run(Node) "run()" or \ref init()
810 ///must be called before using this function.
811 const PredMap &predMap() const { return *_pred;}
813 ///Checks if the given node is reached from the root(s).
815 ///Returns \c true if \c v is reached from the root(s).
817 ///\pre Either \ref run(Node) "run()" or \ref init()
818 ///must be called before using this function.
819 bool reached(Node v) const { return (*_reached)[v]; }
824 ///Default traits class of bfs() function.
826 ///Default traits class of bfs() function.
827 ///\tparam GR Digraph type.
829 struct BfsWizardDefaultTraits
831 ///The type of the digraph the algorithm runs on.
834 ///\brief The type of the map that stores the predecessor
835 ///arcs of the shortest paths.
837 ///The type of the map that stores the predecessor
838 ///arcs of the shortest paths.
839 ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
840 typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
841 ///Instantiates a PredMap.
843 ///This function instantiates a PredMap.
844 ///\param g is the digraph, to which we would like to define the
846 static PredMap *createPredMap(const Digraph &g)
848 return new PredMap(g);
851 ///The type of the map that indicates which nodes are processed.
853 ///The type of the map that indicates which nodes are processed.
854 ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
855 ///By default it is a NullMap.
856 typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
857 ///Instantiates a ProcessedMap.
859 ///This function instantiates a ProcessedMap.
860 ///\param g is the digraph, to which
861 ///we would like to define the ProcessedMap.
863 static ProcessedMap *createProcessedMap(const Digraph &g)
865 static ProcessedMap *createProcessedMap(const Digraph &)
868 return new ProcessedMap();
871 ///The type of the map that indicates which nodes are reached.
873 ///The type of the map that indicates which nodes are reached.
874 ///It must conform to the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
875 typedef typename Digraph::template NodeMap<bool> ReachedMap;
876 ///Instantiates a ReachedMap.
878 ///This function instantiates a ReachedMap.
879 ///\param g is the digraph, to which
880 ///we would like to define the ReachedMap.
881 static ReachedMap *createReachedMap(const Digraph &g)
883 return new ReachedMap(g);
886 ///The type of the map that stores the distances of the nodes.
888 ///The type of the map that stores the distances of the nodes.
889 ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
890 typedef typename Digraph::template NodeMap<int> DistMap;
891 ///Instantiates a DistMap.
893 ///This function instantiates a DistMap.
894 ///\param g is the digraph, to which we would like to define
896 static DistMap *createDistMap(const Digraph &g)
898 return new DistMap(g);
901 ///The type of the shortest paths.
903 ///The type of the shortest paths.
904 ///It must conform to the \ref concepts::Path "Path" concept.
905 typedef lemon::Path<Digraph> Path;
908 /// Default traits class used by BfsWizard
910 /// Default traits class used by BfsWizard.
911 /// \tparam GR The type of the digraph.
913 class BfsWizardBase : public BfsWizardDefaultTraits<GR>
916 typedef BfsWizardDefaultTraits<GR> Base;
918 //The type of the nodes in the digraph.
919 typedef typename Base::Digraph::Node Node;
921 //Pointer to the digraph the algorithm runs on.
923 //Pointer to the map of reached nodes.
925 //Pointer to the map of processed nodes.
927 //Pointer to the map of predecessors arcs.
929 //Pointer to the map of distances.
931 //Pointer to the shortest path to the target node.
933 //Pointer to the distance of the target node.
939 /// This constructor does not require parameters, it initiates
940 /// all of the attributes to \c 0.
941 BfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0),
942 _dist(0), _path(0), _di(0) {}
946 /// This constructor requires one parameter,
947 /// others are initiated to \c 0.
948 /// \param g The digraph the algorithm runs on.
949 BfsWizardBase(const GR &g) :
950 _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
951 _reached(0), _processed(0), _pred(0), _dist(0), _path(0), _di(0) {}
955 /// Auxiliary class for the function-type interface of BFS algorithm.
957 /// This auxiliary class is created to implement the
958 /// \ref bfs() "function-type interface" of \ref Bfs algorithm.
959 /// It does not have own \ref run(Node) "run()" method, it uses the
960 /// functions and features of the plain \ref Bfs.
962 /// This class should only be used through the \ref bfs() function,
963 /// which makes it easier to use the algorithm.
965 class BfsWizard : public TR
969 typedef typename TR::Digraph Digraph;
971 typedef typename Digraph::Node Node;
972 typedef typename Digraph::NodeIt NodeIt;
973 typedef typename Digraph::Arc Arc;
974 typedef typename Digraph::OutArcIt OutArcIt;
976 typedef typename TR::PredMap PredMap;
977 typedef typename TR::DistMap DistMap;
978 typedef typename TR::ReachedMap ReachedMap;
979 typedef typename TR::ProcessedMap ProcessedMap;
980 typedef typename TR::Path Path;
985 BfsWizard() : TR() {}
987 /// Constructor that requires parameters.
989 /// Constructor that requires parameters.
990 /// These parameters will be the default values for the traits class.
991 /// \param g The digraph the algorithm runs on.
992 BfsWizard(const Digraph &g) :
996 BfsWizard(const TR &b) : TR(b) {}
1000 ///Runs BFS algorithm from the given source node.
1002 ///This method runs BFS algorithm from node \c s
1003 ///in order to compute the shortest path to each node.
1006 Bfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
1008 alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1010 alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1012 alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
1013 if (Base::_processed)
1014 alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1021 ///Finds the shortest path between \c s and \c t.
1023 ///This method runs BFS algorithm from node \c s
1024 ///in order to compute the shortest path to node \c t
1025 ///(it stops searching when \c t is processed).
1027 ///\return \c true if \c t is reachable form \c s.
1028 bool run(Node s, Node t)
1030 Bfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
1032 alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1034 alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1036 alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
1037 if (Base::_processed)
1038 alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1041 *reinterpret_cast<Path*>(Base::_path) = alg.path(t);
1043 *Base::_di = alg.dist(t);
1044 return alg.reached(t);
1047 ///Runs BFS algorithm to visit all nodes in the digraph.
1049 ///This method runs BFS algorithm in order to compute
1050 ///the shortest path to each node.
1057 struct SetPredMapBase : public Base {
1059 static PredMap *createPredMap(const Digraph &) { return 0; };
1060 SetPredMapBase(const TR &b) : TR(b) {}
1063 ///\brief \ref named-templ-param "Named parameter" for setting
1064 ///the predecessor map.
1066 ///\ref named-templ-param "Named parameter" function for setting
1067 ///the map that stores the predecessor arcs of the nodes.
1069 BfsWizard<SetPredMapBase<T> > predMap(const T &t)
1071 Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1072 return BfsWizard<SetPredMapBase<T> >(*this);
1076 struct SetReachedMapBase : public Base {
1077 typedef T ReachedMap;
1078 static ReachedMap *createReachedMap(const Digraph &) { return 0; };
1079 SetReachedMapBase(const TR &b) : TR(b) {}
1082 ///\brief \ref named-templ-param "Named parameter" for setting
1085 ///\ref named-templ-param "Named parameter" function for setting
1086 ///the map that indicates which nodes are reached.
1088 BfsWizard<SetReachedMapBase<T> > reachedMap(const T &t)
1090 Base::_reached=reinterpret_cast<void*>(const_cast<T*>(&t));
1091 return BfsWizard<SetReachedMapBase<T> >(*this);
1095 struct SetDistMapBase : public Base {
1097 static DistMap *createDistMap(const Digraph &) { return 0; };
1098 SetDistMapBase(const TR &b) : TR(b) {}
1101 ///\brief \ref named-templ-param "Named parameter" for setting
1102 ///the distance map.
1104 ///\ref named-templ-param "Named parameter" function for setting
1105 ///the map that stores the distances of the nodes calculated
1106 ///by the algorithm.
1108 BfsWizard<SetDistMapBase<T> > distMap(const T &t)
1110 Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1111 return BfsWizard<SetDistMapBase<T> >(*this);
1115 struct SetProcessedMapBase : public Base {
1116 typedef T ProcessedMap;
1117 static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
1118 SetProcessedMapBase(const TR &b) : TR(b) {}
1121 ///\brief \ref named-func-param "Named parameter" for setting
1122 ///the processed map.
1124 ///\ref named-templ-param "Named parameter" function for setting
1125 ///the map that indicates which nodes are processed.
1127 BfsWizard<SetProcessedMapBase<T> > processedMap(const T &t)
1129 Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1130 return BfsWizard<SetProcessedMapBase<T> >(*this);
1134 struct SetPathBase : public Base {
1136 SetPathBase(const TR &b) : TR(b) {}
1138 ///\brief \ref named-func-param "Named parameter"
1139 ///for getting the shortest path to the target node.
1141 ///\ref named-func-param "Named parameter"
1142 ///for getting the shortest path to the target node.
1144 BfsWizard<SetPathBase<T> > path(const T &t)
1146 Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t));
1147 return BfsWizard<SetPathBase<T> >(*this);
1150 ///\brief \ref named-func-param "Named parameter"
1151 ///for getting the distance of the target node.
1153 ///\ref named-func-param "Named parameter"
1154 ///for getting the distance of the target node.
1155 BfsWizard dist(const int &d)
1157 Base::_di=const_cast<int*>(&d);
1163 ///Function-type interface for BFS algorithm.
1166 ///Function-type interface for BFS algorithm.
1168 ///This function also has several \ref named-func-param "named parameters",
1169 ///they are declared as the members of class \ref BfsWizard.
1170 ///The following examples show how to use these parameters.
1172 /// // Compute shortest path from node s to each node
1173 /// bfs(g).predMap(preds).distMap(dists).run(s);
1175 /// // Compute shortest path from s to t
1176 /// bool reached = bfs(g).path(p).dist(d).run(s,t);
1178 ///\warning Don't forget to put the \ref BfsWizard::run(Node) "run()"
1179 ///to the end of the parameter list.
1183 BfsWizard<BfsWizardBase<GR> >
1184 bfs(const GR &digraph)
1186 return BfsWizard<BfsWizardBase<GR> >(digraph);
1190 /// \brief Visitor class for BFS.
1192 /// This class defines the interface of the BfsVisit events, and
1193 /// it could be the base of a real visitor class.
1194 template <typename GR>
1197 typedef typename Digraph::Arc Arc;
1198 typedef typename Digraph::Node Node;
1199 /// \brief Called for the source node(s) of the BFS.
1201 /// This function is called for the source node(s) of the BFS.
1202 void start(const Node& node) {}
1203 /// \brief Called when a node is reached first time.
1205 /// This function is called when a node is reached first time.
1206 void reach(const Node& node) {}
1207 /// \brief Called when a node is processed.
1209 /// This function is called when a node is processed.
1210 void process(const Node& node) {}
1211 /// \brief Called when an arc reaches a new node.
1213 /// This function is called when the BFS finds an arc whose target node
1214 /// is not reached yet.
1215 void discover(const Arc& arc) {}
1216 /// \brief Called when an arc is examined but its target node is
1217 /// already discovered.
1219 /// This function is called when an arc is examined but its target node is
1220 /// already discovered.
1221 void examine(const Arc& arc) {}
1224 template <typename GR>
1227 typedef typename Digraph::Arc Arc;
1228 typedef typename Digraph::Node Node;
1229 void start(const Node&) {}
1230 void reach(const Node&) {}
1231 void process(const Node&) {}
1232 void discover(const Arc&) {}
1233 void examine(const Arc&) {}
1235 template <typename _Visitor>
1236 struct Constraints {
1237 void constraints() {
1240 visitor.start(node);
1241 visitor.reach(node);
1242 visitor.process(node);
1243 visitor.discover(arc);
1244 visitor.examine(arc);
1251 /// \brief Default traits class of BfsVisit class.
1253 /// Default traits class of BfsVisit class.
1254 /// \tparam GR The type of the digraph the algorithm runs on.
1256 struct BfsVisitDefaultTraits {
1258 /// \brief The type of the digraph the algorithm runs on.
1261 /// \brief The type of the map that indicates which nodes are reached.
1263 /// The type of the map that indicates which nodes are reached.
1264 /// It must conform to the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
1265 typedef typename Digraph::template NodeMap<bool> ReachedMap;
1267 /// \brief Instantiates a ReachedMap.
1269 /// This function instantiates a ReachedMap.
1270 /// \param digraph is the digraph, to which
1271 /// we would like to define the ReachedMap.
1272 static ReachedMap *createReachedMap(const Digraph &digraph) {
1273 return new ReachedMap(digraph);
1280 /// \brief BFS algorithm class with visitor interface.
1282 /// This class provides an efficient implementation of the BFS algorithm
1283 /// with visitor interface.
1285 /// The BfsVisit class provides an alternative interface to the Bfs
1286 /// class. It works with callback mechanism, the BfsVisit object calls
1287 /// the member functions of the \c Visitor class on every BFS event.
1289 /// This interface of the BFS algorithm should be used in special cases
1290 /// when extra actions have to be performed in connection with certain
1291 /// events of the BFS algorithm. Otherwise consider to use Bfs or bfs()
1294 /// \tparam GR The type of the digraph the algorithm runs on.
1295 /// The default type is \ref ListDigraph.
1296 /// The value of GR is not used directly by \ref BfsVisit,
1297 /// it is only passed to \ref BfsVisitDefaultTraits.
1298 /// \tparam VS The Visitor type that is used by the algorithm.
1299 /// \ref BfsVisitor "BfsVisitor<GR>" is an empty visitor, which
1300 /// does not observe the BFS events. If you want to observe the BFS
1301 /// events, you should implement your own visitor class.
1302 /// \tparam TR Traits class to set various data types used by the
1303 /// algorithm. The default traits class is
1304 /// \ref BfsVisitDefaultTraits "BfsVisitDefaultTraits<GR>".
1305 /// See \ref BfsVisitDefaultTraits for the documentation of
1306 /// a BFS visit traits class.
1308 template <typename GR, typename VS, typename TR>
1310 template <typename GR = ListDigraph,
1311 typename VS = BfsVisitor<GR>,
1312 typename TR = BfsVisitDefaultTraits<GR> >
1317 ///The traits class.
1320 ///The type of the digraph the algorithm runs on.
1321 typedef typename Traits::Digraph Digraph;
1323 ///The visitor type used by the algorithm.
1326 ///The type of the map that indicates which nodes are reached.
1327 typedef typename Traits::ReachedMap ReachedMap;
1331 typedef typename Digraph::Node Node;
1332 typedef typename Digraph::NodeIt NodeIt;
1333 typedef typename Digraph::Arc Arc;
1334 typedef typename Digraph::OutArcIt OutArcIt;
1336 //Pointer to the underlying digraph.
1337 const Digraph *_digraph;
1338 //Pointer to the visitor object.
1340 //Pointer to the map of reached status of the nodes.
1341 ReachedMap *_reached;
1342 //Indicates if _reached is locally allocated (true) or not.
1345 std::vector<typename Digraph::Node> _list;
1346 int _list_front, _list_back;
1348 //Creates the maps if necessary.
1349 void create_maps() {
1351 local_reached = true;
1352 _reached = Traits::createReachedMap(*_digraph);
1362 typedef BfsVisit Create;
1364 /// \name Named Template Parameters
1368 struct SetReachedMapTraits : public Traits {
1369 typedef T ReachedMap;
1370 static ReachedMap *createReachedMap(const Digraph &digraph) {
1371 LEMON_ASSERT(false, "ReachedMap is not initialized");
1372 return 0; // ignore warnings
1375 /// \brief \ref named-templ-param "Named parameter" for setting
1376 /// ReachedMap type.
1378 /// \ref named-templ-param "Named parameter" for setting ReachedMap type.
1380 struct SetReachedMap : public BfsVisit< Digraph, Visitor,
1381 SetReachedMapTraits<T> > {
1382 typedef BfsVisit< Digraph, Visitor, SetReachedMapTraits<T> > Create;
1388 /// \brief Constructor.
1392 /// \param digraph The digraph the algorithm runs on.
1393 /// \param visitor The visitor object of the algorithm.
1394 BfsVisit(const Digraph& digraph, Visitor& visitor)
1395 : _digraph(&digraph), _visitor(&visitor),
1396 _reached(0), local_reached(false) {}
1398 /// \brief Destructor.
1400 if(local_reached) delete _reached;
1403 /// \brief Sets the map that indicates which nodes are reached.
1405 /// Sets the map that indicates which nodes are reached.
1406 /// If you don't use this function before calling \ref run(Node) "run()"
1407 /// or \ref init(), an instance will be allocated automatically.
1408 /// The destructor deallocates this automatically allocated map,
1410 /// \return <tt> (*this) </tt>
1411 BfsVisit &reachedMap(ReachedMap &m) {
1414 local_reached = false;
1422 /// \name Execution Control
1423 /// The simplest way to execute the BFS algorithm is to use one of the
1424 /// member functions called \ref run(Node) "run()".\n
1425 /// If you need better control on the execution, you have to call
1426 /// \ref init() first, then you can add several source nodes with
1427 /// \ref addSource(). Finally the actual path computation can be
1428 /// performed with one of the \ref start() functions.
1432 /// \brief Initializes the internal data structures.
1434 /// Initializes the internal data structures.
1437 _list.resize(countNodes(*_digraph));
1438 _list_front = _list_back = -1;
1439 for (NodeIt u(*_digraph) ; u != INVALID ; ++u) {
1440 _reached->set(u, false);
1444 /// \brief Adds a new source node.
1446 /// Adds a new source node to the set of nodes to be processed.
1447 void addSource(Node s) {
1448 if(!(*_reached)[s]) {
1449 _reached->set(s,true);
1452 _list[++_list_back] = s;
1456 /// \brief Processes the next node.
1458 /// Processes the next node.
1460 /// \return The processed node.
1462 /// \pre The queue must not be empty.
1463 Node processNextNode() {
1464 Node n = _list[++_list_front];
1465 _visitor->process(n);
1467 for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1468 Node m = _digraph->target(e);
1469 if (!(*_reached)[m]) {
1470 _visitor->discover(e);
1472 _reached->set(m, true);
1473 _list[++_list_back] = m;
1475 _visitor->examine(e);
1481 /// \brief Processes the next node.
1483 /// Processes the next node and checks if the given target node
1484 /// is reached. If the target node is reachable from the processed
1485 /// node, then the \c reach parameter will be set to \c true.
1487 /// \param target The target node.
1488 /// \retval reach Indicates if the target node is reached.
1489 /// It should be initially \c false.
1491 /// \return The processed node.
1493 /// \pre The queue must not be empty.
1494 Node processNextNode(Node target, bool& reach) {
1495 Node n = _list[++_list_front];
1496 _visitor->process(n);
1498 for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1499 Node m = _digraph->target(e);
1500 if (!(*_reached)[m]) {
1501 _visitor->discover(e);
1503 _reached->set(m, true);
1504 _list[++_list_back] = m;
1505 reach = reach || (target == m);
1507 _visitor->examine(e);
1513 /// \brief Processes the next node.
1515 /// Processes the next node and checks if at least one of reached
1516 /// nodes has \c true value in the \c nm node map. If one node
1517 /// with \c true value is reachable from the processed node, then the
1518 /// \c rnode parameter will be set to the first of such nodes.
1520 /// \param nm A \c bool (or convertible) node map that indicates the
1521 /// possible targets.
1522 /// \retval rnode The reached target node.
1523 /// It should be initially \c INVALID.
1525 /// \return The processed node.
1527 /// \pre The queue must not be empty.
1528 template <typename NM>
1529 Node processNextNode(const NM& nm, Node& rnode) {
1530 Node n = _list[++_list_front];
1531 _visitor->process(n);
1533 for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1534 Node m = _digraph->target(e);
1535 if (!(*_reached)[m]) {
1536 _visitor->discover(e);
1538 _reached->set(m, true);
1539 _list[++_list_back] = m;
1540 if (nm[m] && rnode == INVALID) rnode = m;
1542 _visitor->examine(e);
1548 /// \brief The next node to be processed.
1550 /// Returns the next node to be processed or \c INVALID if the queue
1552 Node nextNode() const {
1553 return _list_front != _list_back ? _list[_list_front + 1] : INVALID;
1556 /// \brief Returns \c false if there are nodes
1557 /// to be processed.
1559 /// Returns \c false if there are nodes
1560 /// to be processed in the queue.
1561 bool emptyQueue() const { return _list_front == _list_back; }
1563 /// \brief Returns the number of the nodes to be processed.
1565 /// Returns the number of the nodes to be processed in the queue.
1566 int queueSize() const { return _list_back - _list_front; }
1568 /// \brief Executes the algorithm.
1570 /// Executes the algorithm.
1572 /// This method runs the %BFS algorithm from the root node(s)
1573 /// in order to compute the shortest path to each node.
1575 /// The algorithm computes
1576 /// - the shortest path tree (forest),
1577 /// - the distance of each node from the root(s).
1579 /// \pre init() must be called and at least one root node should be added
1580 /// with addSource() before using this function.
1582 /// \note <tt>b.start()</tt> is just a shortcut of the following code.
1584 /// while ( !b.emptyQueue() ) {
1585 /// b.processNextNode();
1589 while ( !emptyQueue() ) processNextNode();
1592 /// \brief Executes the algorithm until the given target node is reached.
1594 /// Executes the algorithm until the given target node is reached.
1596 /// This method runs the %BFS algorithm from the root node(s)
1597 /// in order to compute the shortest path to \c t.
1599 /// The algorithm computes
1600 /// - the shortest path to \c t,
1601 /// - the distance of \c t from the root(s).
1603 /// \pre init() must be called and at least one root node should be
1604 /// added with addSource() before using this function.
1606 /// \note <tt>b.start(t)</tt> is just a shortcut of the following code.
1608 /// bool reach = false;
1609 /// while ( !b.emptyQueue() && !reach ) {
1610 /// b.processNextNode(t, reach);
1613 void start(Node t) {
1615 while ( !emptyQueue() && !reach ) processNextNode(t, reach);
1618 /// \brief Executes the algorithm until a condition is met.
1620 /// Executes the algorithm until a condition is met.
1622 /// This method runs the %BFS algorithm from the root node(s) in
1623 /// order to compute the shortest path to a node \c v with
1624 /// <tt>nm[v]</tt> true, if such a node can be found.
1626 /// \param nm must be a bool (or convertible) node map. The
1627 /// algorithm will stop when it reaches a node \c v with
1628 /// <tt>nm[v]</tt> true.
1630 /// \return The reached node \c v with <tt>nm[v]</tt> true or
1631 /// \c INVALID if no such node was found.
1633 /// \pre init() must be called and at least one root node should be
1634 /// added with addSource() before using this function.
1636 /// \note <tt>b.start(nm)</tt> is just a shortcut of the following code.
1638 /// Node rnode = INVALID;
1639 /// while ( !b.emptyQueue() && rnode == INVALID ) {
1640 /// b.processNextNode(nm, rnode);
1644 template <typename NM>
1645 Node start(const NM &nm) {
1646 Node rnode = INVALID;
1647 while ( !emptyQueue() && rnode == INVALID ) {
1648 processNextNode(nm, rnode);
1653 /// \brief Runs the algorithm from the given source node.
1655 /// This method runs the %BFS algorithm from node \c s
1656 /// in order to compute the shortest path to each node.
1658 /// The algorithm computes
1659 /// - the shortest path tree,
1660 /// - the distance of each node from the root.
1662 /// \note <tt>b.run(s)</tt> is just a shortcut of the following code.
1674 /// \brief Finds the shortest path between \c s and \c t.
1676 /// This method runs the %BFS algorithm from node \c s
1677 /// in order to compute the shortest path to node \c t
1678 /// (it stops searching when \c t is processed).
1680 /// \return \c true if \c t is reachable form \c s.
1682 /// \note Apart from the return value, <tt>b.run(s,t)</tt> is just a
1683 /// shortcut of the following code.
1689 bool run(Node s,Node t) {
1696 /// \brief Runs the algorithm to visit all nodes in the digraph.
1698 /// This method runs the %BFS algorithm in order to
1699 /// compute the shortest path to each node.
1701 /// The algorithm computes
1702 /// - the shortest path tree (forest),
1703 /// - the distance of each node from the root(s).
1705 /// \note <tt>b.run(s)</tt> is just a shortcut of the following code.
1708 /// for (NodeIt n(gr); n != INVALID; ++n) {
1709 /// if (!b.reached(n)) {
1717 for (NodeIt it(*_digraph); it != INVALID; ++it) {
1727 /// \name Query Functions
1728 /// The results of the BFS algorithm can be obtained using these
1730 /// Either \ref run(Node) "run()" or \ref start() should be called
1731 /// before using them.
1735 /// \brief Checks if the given node is reached from the root(s).
1737 /// Returns \c true if \c v is reached from the root(s).
1739 /// \pre Either \ref run(Node) "run()" or \ref init()
1740 /// must be called before using this function.
1741 bool reached(Node v) const { return (*_reached)[v]; }
1747 } //END OF NAMESPACE LEMON