1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
3 * This file is a part of LEMON, a generic C++ optimization library.
5 * Copyright (C) 2003-2008
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
9 * Permission to use, modify and distribute this software is granted
10 * provided that this copyright notice appears in all copies. For
11 * precise terms see the accompanying LICENSE file.
13 * This software is provided "AS IS" with no warranty of any kind,
14 * express or implied, and with no claim as to its suitability for any
24 ///\brief BFS algorithm.
26 #include <lemon/list_graph.h>
27 #include <lemon/bits/path_dump.h>
28 #include <lemon/core.h>
29 #include <lemon/error.h>
30 #include <lemon/maps.h>
31 #include <lemon/path.h>
35 ///Default traits class of Bfs class.
37 ///Default traits class of Bfs class.
38 ///\tparam GR Digraph type.
40 struct BfsDefaultTraits
42 ///The type of the digraph the algorithm runs on.
45 ///\brief The type of the map that stores the predecessor
46 ///arcs of the shortest paths.
48 ///The type of the map that stores the predecessor
49 ///arcs of the shortest paths.
50 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
51 typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
52 ///Instantiates a \ref PredMap.
54 ///This function instantiates a \ref PredMap.
55 ///\param g is the digraph, to which we would like to define the
57 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 meet the \ref concepts::WriteMap "WriteMap" concept.
66 typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
67 ///Instantiates a \ref ProcessedMap.
69 ///This function instantiates a \ref ProcessedMap.
70 ///\param g is the digraph, to which
71 ///we would like to define the \ref ProcessedMap
73 static ProcessedMap *createProcessedMap(const Digraph &g)
75 static ProcessedMap *createProcessedMap(const Digraph &)
78 return new ProcessedMap();
81 ///The type of the map that indicates which nodes are reached.
83 ///The type of the map that indicates which nodes are reached.
84 ///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
85 typedef typename Digraph::template NodeMap<bool> ReachedMap;
86 ///Instantiates a \ref ReachedMap.
88 ///This function instantiates a \ref ReachedMap.
89 ///\param g is the digraph, to which
90 ///we would like to define the \ref ReachedMap.
91 static ReachedMap *createReachedMap(const Digraph &g)
93 return new ReachedMap(g);
96 ///The type of the map that stores the distances of the nodes.
98 ///The type of the map that stores the distances of the nodes.
99 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
100 typedef typename Digraph::template NodeMap<int> DistMap;
101 ///Instantiates a \ref DistMap.
103 ///This function instantiates a \ref DistMap.
104 ///\param g is the digraph, to which we would like to define the
106 static DistMap *createDistMap(const Digraph &g)
108 return new DistMap(g);
112 ///%BFS algorithm class.
115 ///This class provides an efficient implementation of the %BFS algorithm.
117 ///There is also a \ref bfs() "function-type interface" for the BFS
118 ///algorithm, which is convenient in the simplier cases and it can be
121 ///\tparam GR The type of the digraph the algorithm runs on.
122 ///The default value is \ref ListDigraph. The value of GR is not used
123 ///directly by \ref Bfs, it is only passed to \ref BfsDefaultTraits.
124 ///\tparam TR Traits class to set various data types used by the algorithm.
125 ///The default traits class is
126 ///\ref BfsDefaultTraits "BfsDefaultTraits<GR>".
127 ///See \ref BfsDefaultTraits for the documentation of
128 ///a Bfs traits class.
130 template <typename GR,
133 template <typename GR=ListDigraph,
134 typename TR=BfsDefaultTraits<GR> >
139 ///The type of the digraph the algorithm runs on.
140 typedef typename TR::Digraph Digraph;
142 ///\brief The type of the map that stores the predecessor arcs of the
144 typedef typename TR::PredMap PredMap;
145 ///The type of the map that stores the distances of the nodes.
146 typedef typename TR::DistMap DistMap;
147 ///The type of the map that indicates which nodes are reached.
148 typedef typename TR::ReachedMap ReachedMap;
149 ///The type of the map that indicates which nodes are processed.
150 typedef typename TR::ProcessedMap ProcessedMap;
151 ///The type of the paths.
152 typedef PredMapPath<Digraph, PredMap> Path;
159 typedef typename Digraph::Node Node;
160 typedef typename Digraph::NodeIt NodeIt;
161 typedef typename Digraph::Arc Arc;
162 typedef typename Digraph::OutArcIt OutArcIt;
164 //Pointer to the underlying digraph.
166 //Pointer to the map of predecessor arcs.
168 //Indicates if _pred is locally allocated (true) or not.
170 //Pointer to the map of distances.
172 //Indicates if _dist is locally allocated (true) or not.
174 //Pointer to the map of reached status of the nodes.
175 ReachedMap *_reached;
176 //Indicates if _reached is locally allocated (true) or not.
178 //Pointer to the map of processed status of the nodes.
179 ProcessedMap *_processed;
180 //Indicates if _processed is locally allocated (true) or not.
181 bool local_processed;
183 std::vector<typename Digraph::Node> _queue;
184 int _queue_head,_queue_tail,_queue_next_dist;
187 //Creates the maps if necessary.
192 _pred = Traits::createPredMap(*G);
196 _dist = Traits::createDistMap(*G);
199 local_reached = true;
200 _reached = Traits::createReachedMap(*G);
203 local_processed = true;
204 _processed = Traits::createProcessedMap(*G);
216 ///\name Named template parameters
221 struct SetPredMapTraits : public Traits {
223 static PredMap *createPredMap(const Digraph &)
225 LEMON_ASSERT(false, "PredMap is not initialized");
226 return 0; // ignore warnings
229 ///\brief \ref named-templ-param "Named parameter" for setting
230 ///\ref PredMap type.
232 ///\ref named-templ-param "Named parameter" for setting
233 ///\ref PredMap type.
235 struct SetPredMap : public Bfs< Digraph, SetPredMapTraits<T> > {
236 typedef Bfs< Digraph, SetPredMapTraits<T> > Create;
240 struct SetDistMapTraits : public Traits {
242 static DistMap *createDistMap(const Digraph &)
244 LEMON_ASSERT(false, "DistMap is not initialized");
245 return 0; // ignore warnings
248 ///\brief \ref named-templ-param "Named parameter" for setting
249 ///\ref DistMap type.
251 ///\ref named-templ-param "Named parameter" for setting
252 ///\ref DistMap type.
254 struct SetDistMap : public Bfs< Digraph, SetDistMapTraits<T> > {
255 typedef Bfs< Digraph, SetDistMapTraits<T> > Create;
259 struct SetReachedMapTraits : public Traits {
260 typedef T ReachedMap;
261 static ReachedMap *createReachedMap(const Digraph &)
263 LEMON_ASSERT(false, "ReachedMap is not initialized");
264 return 0; // ignore warnings
267 ///\brief \ref named-templ-param "Named parameter" for setting
268 ///\ref ReachedMap type.
270 ///\ref named-templ-param "Named parameter" for setting
271 ///\ref ReachedMap type.
273 struct SetReachedMap : public Bfs< Digraph, SetReachedMapTraits<T> > {
274 typedef Bfs< Digraph, SetReachedMapTraits<T> > Create;
278 struct SetProcessedMapTraits : public Traits {
279 typedef T ProcessedMap;
280 static ProcessedMap *createProcessedMap(const Digraph &)
282 LEMON_ASSERT(false, "ProcessedMap is not initialized");
283 return 0; // ignore warnings
286 ///\brief \ref named-templ-param "Named parameter" for setting
287 ///\ref ProcessedMap type.
289 ///\ref named-templ-param "Named parameter" for setting
290 ///\ref ProcessedMap type.
292 struct SetProcessedMap : public Bfs< Digraph, SetProcessedMapTraits<T> > {
293 typedef Bfs< Digraph, SetProcessedMapTraits<T> > Create;
296 struct SetStandardProcessedMapTraits : public Traits {
297 typedef typename Digraph::template NodeMap<bool> ProcessedMap;
298 static ProcessedMap *createProcessedMap(const Digraph &g)
300 return new ProcessedMap(g);
301 return 0; // ignore warnings
304 ///\brief \ref named-templ-param "Named parameter" for setting
305 ///\ref ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
307 ///\ref named-templ-param "Named parameter" for setting
308 ///\ref ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
309 ///If you don't set it explicitly, it will be automatically allocated.
310 struct SetStandardProcessedMap :
311 public Bfs< Digraph, SetStandardProcessedMapTraits > {
312 typedef Bfs< Digraph, SetStandardProcessedMapTraits > Create;
322 ///\param g The digraph the algorithm runs on.
323 Bfs(const Digraph &g) :
325 _pred(NULL), local_pred(false),
326 _dist(NULL), local_dist(false),
327 _reached(NULL), local_reached(false),
328 _processed(NULL), local_processed(false)
334 if(local_pred) delete _pred;
335 if(local_dist) delete _dist;
336 if(local_reached) delete _reached;
337 if(local_processed) delete _processed;
340 ///Sets the map that stores the predecessor arcs.
342 ///Sets the map that stores the predecessor arcs.
343 ///If you don't use this function before calling \ref run(),
344 ///it will allocate one. The destructor deallocates this
345 ///automatically allocated map, of course.
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(),
361 ///it will allocate one. The destructor deallocates this
362 ///automatically allocated map, of course.
363 ///\return <tt> (*this) </tt>
364 Bfs &reachedMap(ReachedMap &m)
374 ///Sets the map that indicates which nodes are processed.
376 ///Sets the map that indicates which nodes are processed.
377 ///If you don't use this function before calling \ref run(),
378 ///it will allocate one. The destructor deallocates this
379 ///automatically allocated map, of course.
380 ///\return <tt> (*this) </tt>
381 Bfs &processedMap(ProcessedMap &m)
383 if(local_processed) {
385 local_processed=false;
391 ///Sets the map that stores the distances of the nodes.
393 ///Sets the map that stores the distances of the nodes calculated by
395 ///If you don't use this function before calling \ref run(),
396 ///it will allocate one. The destructor deallocates this
397 ///automatically allocated map, of course.
398 ///\return <tt> (*this) </tt>
399 Bfs &distMap(DistMap &m)
411 ///\name Execution control
412 ///The simplest way to execute the algorithm is to use
413 ///one of the member functions called \ref lemon::Bfs::run() "run()".
415 ///If you need more control on the execution, first you must call
416 ///\ref lemon::Bfs::init() "init()", then you can add several source
417 ///nodes with \ref lemon::Bfs::addSource() "addSource()".
418 ///Finally \ref lemon::Bfs::start() "start()" will perform the
419 ///actual path computation.
423 ///Initializes the internal data structures.
425 ///Initializes the internal data structures.
430 _queue.resize(countNodes(*G));
431 _queue_head=_queue_tail=0;
433 for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
434 _pred->set(u,INVALID);
435 _reached->set(u,false);
436 _processed->set(u,false);
440 ///Adds a new source node.
442 ///Adds a new source node to the set of nodes to be processed.
444 void addSource(Node s)
448 _reached->set(s,true);
449 _pred->set(s,INVALID);
451 _queue[_queue_head++]=s;
452 _queue_next_dist=_queue_head;
456 ///Processes the next node.
458 ///Processes the next node.
460 ///\return The processed node.
462 ///\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 ///\brief Returns \c false if there are nodes
563 ///Returns \c false if there are nodes
564 ///to be processed in the queue.
565 bool emptyQueue() const { return _queue_tail==_queue_head; }
567 ///Returns the number of the nodes to be processed.
569 ///Returns the number of the nodes to be processed in the queue.
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 result of the %BFS algorithm can be obtained using these
736 ///Either \ref lemon::Bfs::run() "run()" or \ref lemon::Bfs::start()
737 ///"start()" must be called before using them.
741 ///The shortest path to a node.
743 ///Returns the shortest path to a node.
745 ///\warning \c t should be reachable from the root(s).
747 ///\pre Either \ref run() or \ref start() must be called before
748 ///using this function.
749 Path path(Node t) const { return Path(*G, *_pred, t); }
751 ///The distance of a node from the root(s).
753 ///Returns the distance of a node from the root(s).
755 ///\warning If node \c v is not reachable from the root(s), then
756 ///the return value of this function is undefined.
758 ///\pre Either \ref run() or \ref start() must be called before
759 ///using this function.
760 int dist(Node v) const { return (*_dist)[v]; }
762 ///Returns the 'previous arc' of the shortest path tree for a node.
764 ///This function returns the 'previous arc' of the shortest path
765 ///tree for the node \c v, i.e. it returns the last arc of a
766 ///shortest path from the root(s) to \c v. It is \c INVALID if \c v
767 ///is not reachable from the root(s) or if \c v is a root.
769 ///The shortest path tree used here is equal to the shortest path
770 ///tree used in \ref predNode().
772 ///\pre Either \ref run() or \ref start() must be called before
773 ///using this function.
774 Arc predArc(Node v) const { return (*_pred)[v];}
776 ///Returns the 'previous node' of the shortest path tree for a node.
778 ///This function returns the 'previous node' of the shortest path
779 ///tree for the node \c v, i.e. it returns the last but one node
780 ///from a shortest path from the root(s) to \c v. It is \c INVALID
781 ///if \c v is not reachable from the root(s) or if \c v is a root.
783 ///The shortest path tree used here is equal to the shortest path
784 ///tree used in \ref predArc().
786 ///\pre Either \ref run() or \ref start() must be called before
787 ///using this function.
788 Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
789 G->source((*_pred)[v]); }
791 ///\brief Returns a const reference to the node map that stores the
792 /// distances of the nodes.
794 ///Returns a const reference to the node map that stores the distances
795 ///of the nodes calculated by the algorithm.
797 ///\pre Either \ref run() or \ref init()
798 ///must be called before using this function.
799 const DistMap &distMap() const { return *_dist;}
801 ///\brief Returns a const reference to the node map that stores the
804 ///Returns a const reference to the node map that stores the predecessor
805 ///arcs, which form the shortest path tree.
807 ///\pre Either \ref run() or \ref init()
808 ///must be called before using this function.
809 const PredMap &predMap() const { return *_pred;}
811 ///Checks if a node is reachable from the root(s).
813 ///Returns \c true if \c v is reachable from the root(s).
814 ///\pre Either \ref run() or \ref start()
815 ///must be called before using this function.
816 bool reached(Node v) const { return (*_reached)[v]; }
821 ///Default traits class of bfs() function.
823 ///Default traits class of bfs() function.
824 ///\tparam GR Digraph type.
826 struct BfsWizardDefaultTraits
828 ///The type of the digraph the algorithm runs on.
831 ///\brief The type of the map that stores the predecessor
832 ///arcs of the shortest paths.
834 ///The type of the map that stores the predecessor
835 ///arcs of the shortest paths.
836 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
837 typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
838 ///Instantiates a \ref PredMap.
840 ///This function instantiates a \ref PredMap.
841 ///\param g is the digraph, to which we would like to define the
843 static PredMap *createPredMap(const Digraph &g)
845 return new PredMap(g);
848 ///The type of the map that indicates which nodes are processed.
850 ///The type of the map that indicates which nodes are processed.
851 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
852 ///By default it is a NullMap.
853 typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
854 ///Instantiates a \ref ProcessedMap.
856 ///This function instantiates a \ref ProcessedMap.
857 ///\param g is the digraph, to which
858 ///we would like to define the \ref ProcessedMap.
860 static ProcessedMap *createProcessedMap(const Digraph &g)
862 static ProcessedMap *createProcessedMap(const Digraph &)
865 return new ProcessedMap();
868 ///The type of the map that indicates which nodes are reached.
870 ///The type of the map that indicates which nodes are reached.
871 ///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
872 typedef typename Digraph::template NodeMap<bool> ReachedMap;
873 ///Instantiates a \ref ReachedMap.
875 ///This function instantiates a \ref ReachedMap.
876 ///\param g is the digraph, to which
877 ///we would like to define the \ref ReachedMap.
878 static ReachedMap *createReachedMap(const Digraph &g)
880 return new ReachedMap(g);
883 ///The type of the map that stores the distances of the nodes.
885 ///The type of the map that stores the distances of the nodes.
886 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
887 typedef typename Digraph::template NodeMap<int> DistMap;
888 ///Instantiates a \ref DistMap.
890 ///This function instantiates a \ref DistMap.
891 ///\param g is the digraph, to which we would like to define
893 static DistMap *createDistMap(const Digraph &g)
895 return new DistMap(g);
898 ///The type of the shortest paths.
900 ///The type of the shortest paths.
901 ///It must meet the \ref concepts::Path "Path" concept.
902 typedef lemon::Path<Digraph> Path;
905 /// Default traits class used by \ref BfsWizard
907 /// To make it easier to use Bfs algorithm
908 /// we have created a wizard class.
909 /// This \ref BfsWizard class needs default traits,
910 /// as well as the \ref Bfs class.
911 /// The \ref BfsWizardBase is a class to be the default traits of the
912 /// \ref BfsWizard class.
914 class BfsWizardBase : public BfsWizardDefaultTraits<GR>
917 typedef BfsWizardDefaultTraits<GR> Base;
919 //The type of the nodes in the digraph.
920 typedef typename Base::Digraph::Node Node;
922 //Pointer to the digraph the algorithm runs on.
924 //Pointer to the map of reached nodes.
926 //Pointer to the map of processed nodes.
928 //Pointer to the map of predecessors arcs.
930 //Pointer to the map of distances.
932 //Pointer to the shortest path to the target node.
934 //Pointer to the distance of the target node.
940 /// This constructor does not require parameters, therefore it initiates
941 /// all of the attributes to \c 0.
942 BfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0),
943 _dist(0), _path(0), _di(0) {}
947 /// This constructor requires one parameter,
948 /// others are initiated to \c 0.
949 /// \param g The digraph the algorithm runs on.
950 BfsWizardBase(const GR &g) :
951 _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
952 _reached(0), _processed(0), _pred(0), _dist(0), _path(0), _di(0) {}
956 /// Auxiliary class for the function-type interface of BFS algorithm.
958 /// This auxiliary class is created to implement the
959 /// \ref bfs() "function-type interface" of \ref Bfs algorithm.
960 /// It does not have own \ref run() method, it uses the functions
961 /// and features of the plain \ref Bfs.
963 /// This class should only be used through the \ref bfs() function,
964 /// which makes it easier to use the algorithm.
966 class BfsWizard : public TR
970 ///The type of the digraph the algorithm runs on.
971 typedef typename TR::Digraph Digraph;
973 typedef typename Digraph::Node Node;
974 typedef typename Digraph::NodeIt NodeIt;
975 typedef typename Digraph::Arc Arc;
976 typedef typename Digraph::OutArcIt OutArcIt;
978 ///\brief The type of the map that stores the predecessor
979 ///arcs of the shortest paths.
980 typedef typename TR::PredMap PredMap;
981 ///\brief The type of the map that stores the distances of the nodes.
982 typedef typename TR::DistMap DistMap;
983 ///\brief The type of the map that indicates which nodes are reached.
984 typedef typename TR::ReachedMap ReachedMap;
985 ///\brief The type of the map that indicates which nodes are processed.
986 typedef typename TR::ProcessedMap ProcessedMap;
987 ///The type of the shortest paths
988 typedef typename TR::Path Path;
993 BfsWizard() : TR() {}
995 /// Constructor that requires parameters.
997 /// Constructor that requires parameters.
998 /// These parameters will be the default values for the traits class.
999 /// \param g The digraph the algorithm runs on.
1000 BfsWizard(const Digraph &g) :
1004 BfsWizard(const TR &b) : TR(b) {}
1008 ///Runs BFS algorithm from the given source node.
1010 ///This method runs BFS algorithm from node \c s
1011 ///in order to compute the shortest path to each node.
1014 Bfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
1016 alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1018 alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1020 alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
1021 if (Base::_processed)
1022 alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1029 ///Finds the shortest path between \c s and \c t.
1031 ///This method runs BFS algorithm from node \c s
1032 ///in order to compute the shortest path to node \c t
1033 ///(it stops searching when \c t is processed).
1035 ///\return \c true if \c t is reachable form \c s.
1036 bool run(Node s, Node t)
1038 Bfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
1040 alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1042 alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1044 alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
1045 if (Base::_processed)
1046 alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1049 *reinterpret_cast<Path*>(Base::_path) = alg.path(t);
1051 *Base::_di = alg.dist(t);
1052 return alg.reached(t);
1055 ///Runs BFS algorithm to visit all nodes in the digraph.
1057 ///This method runs BFS algorithm in order to compute
1058 ///the shortest path to each node.
1065 struct SetPredMapBase : public Base {
1067 static PredMap *createPredMap(const Digraph &) { return 0; };
1068 SetPredMapBase(const TR &b) : TR(b) {}
1070 ///\brief \ref named-func-param "Named parameter"
1071 ///for setting \ref PredMap object.
1073 ///\ref named-func-param "Named parameter"
1074 ///for setting \ref PredMap object.
1076 BfsWizard<SetPredMapBase<T> > predMap(const T &t)
1078 Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1079 return BfsWizard<SetPredMapBase<T> >(*this);
1083 struct SetReachedMapBase : public Base {
1084 typedef T ReachedMap;
1085 static ReachedMap *createReachedMap(const Digraph &) { return 0; };
1086 SetReachedMapBase(const TR &b) : TR(b) {}
1088 ///\brief \ref named-func-param "Named parameter"
1089 ///for setting \ref ReachedMap object.
1091 /// \ref named-func-param "Named parameter"
1092 ///for setting \ref ReachedMap object.
1094 BfsWizard<SetReachedMapBase<T> > reachedMap(const T &t)
1096 Base::_reached=reinterpret_cast<void*>(const_cast<T*>(&t));
1097 return BfsWizard<SetReachedMapBase<T> >(*this);
1101 struct SetDistMapBase : public Base {
1103 static DistMap *createDistMap(const Digraph &) { return 0; };
1104 SetDistMapBase(const TR &b) : TR(b) {}
1106 ///\brief \ref named-func-param "Named parameter"
1107 ///for setting \ref DistMap object.
1109 /// \ref named-func-param "Named parameter"
1110 ///for setting \ref DistMap object.
1112 BfsWizard<SetDistMapBase<T> > distMap(const T &t)
1114 Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1115 return BfsWizard<SetDistMapBase<T> >(*this);
1119 struct SetProcessedMapBase : public Base {
1120 typedef T ProcessedMap;
1121 static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
1122 SetProcessedMapBase(const TR &b) : TR(b) {}
1124 ///\brief \ref named-func-param "Named parameter"
1125 ///for setting \ref ProcessedMap object.
1127 /// \ref named-func-param "Named parameter"
1128 ///for setting \ref ProcessedMap object.
1130 BfsWizard<SetProcessedMapBase<T> > processedMap(const T &t)
1132 Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1133 return BfsWizard<SetProcessedMapBase<T> >(*this);
1137 struct SetPathBase : public Base {
1139 SetPathBase(const TR &b) : TR(b) {}
1141 ///\brief \ref named-func-param "Named parameter"
1142 ///for getting the shortest path to the target node.
1144 ///\ref named-func-param "Named parameter"
1145 ///for getting the shortest path to the target node.
1147 BfsWizard<SetPathBase<T> > path(const T &t)
1149 Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t));
1150 return BfsWizard<SetPathBase<T> >(*this);
1153 ///\brief \ref named-func-param "Named parameter"
1154 ///for getting the distance of the target node.
1156 ///\ref named-func-param "Named parameter"
1157 ///for getting the distance of the target node.
1158 BfsWizard dist(const int &d)
1160 Base::_di=const_cast<int*>(&d);
1166 ///Function-type interface for BFS algorithm.
1169 ///Function-type interface for BFS algorithm.
1171 ///This function also has several \ref named-func-param "named parameters",
1172 ///they are declared as the members of class \ref BfsWizard.
1173 ///The following examples show how to use these parameters.
1175 /// // Compute shortest path from node s to each node
1176 /// bfs(g).predMap(preds).distMap(dists).run(s);
1178 /// // Compute shortest path from s to t
1179 /// bool reached = bfs(g).path(p).dist(d).run(s,t);
1181 ///\warning Don't forget to put the \ref BfsWizard::run() "run()"
1182 ///to the end of the parameter list.
1186 BfsWizard<BfsWizardBase<GR> >
1187 bfs(const GR &digraph)
1189 return BfsWizard<BfsWizardBase<GR> >(digraph);
1193 /// \brief Visitor class for BFS.
1195 /// This class defines the interface of the BfsVisit events, and
1196 /// it could be the base of a real visitor class.
1197 template <typename _Digraph>
1199 typedef _Digraph Digraph;
1200 typedef typename Digraph::Arc Arc;
1201 typedef typename Digraph::Node Node;
1202 /// \brief Called for the source node(s) of the BFS.
1204 /// This function is called for the source node(s) of the BFS.
1205 void start(const Node& node) {}
1206 /// \brief Called when a node is reached first time.
1208 /// This function is called when a node is reached first time.
1209 void reach(const Node& node) {}
1210 /// \brief Called when a node is processed.
1212 /// This function is called when a node is processed.
1213 void process(const Node& node) {}
1214 /// \brief Called when an arc reaches a new node.
1216 /// This function is called when the BFS finds an arc whose target node
1217 /// is not reached yet.
1218 void discover(const Arc& arc) {}
1219 /// \brief Called when an arc is examined but its target node is
1220 /// already discovered.
1222 /// This function is called when an arc is examined but its target node is
1223 /// already discovered.
1224 void examine(const Arc& arc) {}
1227 template <typename _Digraph>
1229 typedef _Digraph Digraph;
1230 typedef typename Digraph::Arc Arc;
1231 typedef typename Digraph::Node Node;
1232 void start(const Node&) {}
1233 void reach(const Node&) {}
1234 void process(const Node&) {}
1235 void discover(const Arc&) {}
1236 void examine(const Arc&) {}
1238 template <typename _Visitor>
1239 struct Constraints {
1240 void constraints() {
1243 visitor.start(node);
1244 visitor.reach(node);
1245 visitor.process(node);
1246 visitor.discover(arc);
1247 visitor.examine(arc);
1254 /// \brief Default traits class of BfsVisit class.
1256 /// Default traits class of BfsVisit class.
1257 /// \tparam _Digraph The type of the digraph the algorithm runs on.
1258 template<class _Digraph>
1259 struct BfsVisitDefaultTraits {
1261 /// \brief The type of the digraph the algorithm runs on.
1262 typedef _Digraph Digraph;
1264 /// \brief The type of the map that indicates which nodes are reached.
1266 /// The type of the map that indicates which nodes are reached.
1267 /// It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
1268 typedef typename Digraph::template NodeMap<bool> ReachedMap;
1270 /// \brief Instantiates a \ref ReachedMap.
1272 /// This function instantiates a \ref ReachedMap.
1273 /// \param digraph is the digraph, to which
1274 /// we would like to define the \ref ReachedMap.
1275 static ReachedMap *createReachedMap(const Digraph &digraph) {
1276 return new ReachedMap(digraph);
1283 /// \brief %BFS algorithm class with visitor interface.
1285 /// This class provides an efficient implementation of the %BFS algorithm
1286 /// with visitor interface.
1288 /// The %BfsVisit class provides an alternative interface to the Bfs
1289 /// class. It works with callback mechanism, the BfsVisit object calls
1290 /// the member functions of the \c Visitor class on every BFS event.
1292 /// This interface of the BFS algorithm should be used in special cases
1293 /// when extra actions have to be performed in connection with certain
1294 /// events of the BFS algorithm. Otherwise consider to use Bfs or bfs()
1297 /// \tparam _Digraph The type of the digraph the algorithm runs on.
1298 /// The default value is
1299 /// \ref ListDigraph. The value of _Digraph is not used directly by
1300 /// \ref BfsVisit, it is only passed to \ref BfsVisitDefaultTraits.
1301 /// \tparam _Visitor The Visitor type that is used by the algorithm.
1302 /// \ref BfsVisitor "BfsVisitor<_Digraph>" is an empty visitor, which
1303 /// does not observe the BFS events. If you want to observe the BFS
1304 /// events, you should implement your own visitor class.
1305 /// \tparam _Traits Traits class to set various data types used by the
1306 /// algorithm. The default traits class is
1307 /// \ref BfsVisitDefaultTraits "BfsVisitDefaultTraits<_Digraph>".
1308 /// See \ref BfsVisitDefaultTraits for the documentation of
1309 /// a BFS visit traits class.
1311 template <typename _Digraph, typename _Visitor, typename _Traits>
1313 template <typename _Digraph = ListDigraph,
1314 typename _Visitor = BfsVisitor<_Digraph>,
1315 typename _Traits = BfsVisitDefaultTraits<_Digraph> >
1320 ///The traits class.
1321 typedef _Traits Traits;
1323 ///The type of the digraph the algorithm runs on.
1324 typedef typename Traits::Digraph Digraph;
1326 ///The visitor type used by the algorithm.
1327 typedef _Visitor Visitor;
1329 ///The type of the map that indicates which nodes are reached.
1330 typedef typename Traits::ReachedMap ReachedMap;
1334 typedef typename Digraph::Node Node;
1335 typedef typename Digraph::NodeIt NodeIt;
1336 typedef typename Digraph::Arc Arc;
1337 typedef typename Digraph::OutArcIt OutArcIt;
1339 //Pointer to the underlying digraph.
1340 const Digraph *_digraph;
1341 //Pointer to the visitor object.
1343 //Pointer to the map of reached status of the nodes.
1344 ReachedMap *_reached;
1345 //Indicates if _reached is locally allocated (true) or not.
1348 std::vector<typename Digraph::Node> _list;
1349 int _list_front, _list_back;
1351 //Creates the maps if necessary.
1352 void create_maps() {
1354 local_reached = true;
1355 _reached = Traits::createReachedMap(*_digraph);
1365 typedef BfsVisit Create;
1367 /// \name Named template parameters
1371 struct SetReachedMapTraits : public Traits {
1372 typedef T ReachedMap;
1373 static ReachedMap *createReachedMap(const Digraph &digraph) {
1374 LEMON_ASSERT(false, "ReachedMap is not initialized");
1375 return 0; // ignore warnings
1378 /// \brief \ref named-templ-param "Named parameter" for setting
1379 /// ReachedMap type.
1381 /// \ref named-templ-param "Named parameter" for setting ReachedMap type.
1383 struct SetReachedMap : public BfsVisit< Digraph, Visitor,
1384 SetReachedMapTraits<T> > {
1385 typedef BfsVisit< Digraph, Visitor, SetReachedMapTraits<T> > Create;
1391 /// \brief Constructor.
1395 /// \param digraph The digraph the algorithm runs on.
1396 /// \param visitor The visitor object of the algorithm.
1397 BfsVisit(const Digraph& digraph, Visitor& visitor)
1398 : _digraph(&digraph), _visitor(&visitor),
1399 _reached(0), local_reached(false) {}
1401 /// \brief Destructor.
1403 if(local_reached) delete _reached;
1406 /// \brief Sets the map that indicates which nodes are reached.
1408 /// Sets the map that indicates which nodes are reached.
1409 /// If you don't use this function before calling \ref run(),
1410 /// it will allocate one. The destructor deallocates this
1411 /// automatically allocated map, of course.
1412 /// \return <tt> (*this) </tt>
1413 BfsVisit &reachedMap(ReachedMap &m) {
1416 local_reached = false;
1424 /// \name Execution control
1425 /// The simplest way to execute the algorithm is to use
1426 /// one of the member functions called \ref lemon::BfsVisit::run()
1429 /// If you need more control on the execution, first you must call
1430 /// \ref lemon::BfsVisit::init() "init()", then you can add several
1431 /// source nodes with \ref lemon::BfsVisit::addSource() "addSource()".
1432 /// Finally \ref lemon::BfsVisit::start() "start()" will perform the
1433 /// actual path computation.
1437 /// \brief Initializes the internal data structures.
1439 /// Initializes the internal data structures.
1442 _list.resize(countNodes(*_digraph));
1443 _list_front = _list_back = -1;
1444 for (NodeIt u(*_digraph) ; u != INVALID ; ++u) {
1445 _reached->set(u, false);
1449 /// \brief Adds a new source node.
1451 /// Adds a new source node to the set of nodes to be processed.
1452 void addSource(Node s) {
1453 if(!(*_reached)[s]) {
1454 _reached->set(s,true);
1457 _list[++_list_back] = s;
1461 /// \brief Processes the next node.
1463 /// Processes the next node.
1465 /// \return The processed node.
1467 /// \pre The queue must not be empty.
1468 Node processNextNode() {
1469 Node n = _list[++_list_front];
1470 _visitor->process(n);
1472 for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1473 Node m = _digraph->target(e);
1474 if (!(*_reached)[m]) {
1475 _visitor->discover(e);
1477 _reached->set(m, true);
1478 _list[++_list_back] = m;
1480 _visitor->examine(e);
1486 /// \brief Processes the next node.
1488 /// Processes the next node and checks if the given target node
1489 /// is reached. If the target node is reachable from the processed
1490 /// node, then the \c reach parameter will be set to \c true.
1492 /// \param target The target node.
1493 /// \retval reach Indicates if the target node is reached.
1494 /// It should be initially \c false.
1496 /// \return The processed node.
1498 /// \pre The queue must not be empty.
1499 Node processNextNode(Node target, bool& reach) {
1500 Node n = _list[++_list_front];
1501 _visitor->process(n);
1503 for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1504 Node m = _digraph->target(e);
1505 if (!(*_reached)[m]) {
1506 _visitor->discover(e);
1508 _reached->set(m, true);
1509 _list[++_list_back] = m;
1510 reach = reach || (target == m);
1512 _visitor->examine(e);
1518 /// \brief Processes the next node.
1520 /// Processes the next node and checks if at least one of reached
1521 /// nodes has \c true value in the \c nm node map. If one node
1522 /// with \c true value is reachable from the processed node, then the
1523 /// \c rnode parameter will be set to the first of such nodes.
1525 /// \param nm A \c bool (or convertible) node map that indicates the
1526 /// possible targets.
1527 /// \retval rnode The reached target node.
1528 /// It should be initially \c INVALID.
1530 /// \return The processed node.
1532 /// \pre The queue must not be empty.
1533 template <typename NM>
1534 Node processNextNode(const NM& nm, Node& rnode) {
1535 Node n = _list[++_list_front];
1536 _visitor->process(n);
1538 for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1539 Node m = _digraph->target(e);
1540 if (!(*_reached)[m]) {
1541 _visitor->discover(e);
1543 _reached->set(m, true);
1544 _list[++_list_back] = m;
1545 if (nm[m] && rnode == INVALID) rnode = m;
1547 _visitor->examine(e);
1553 /// \brief The next node to be processed.
1555 /// Returns the next node to be processed or \c INVALID if the queue
1557 Node nextNode() const {
1558 return _list_front != _list_back ? _list[_list_front + 1] : INVALID;
1561 /// \brief Returns \c false if there are nodes
1562 /// to be processed.
1564 /// Returns \c false if there are nodes
1565 /// to be processed in the queue.
1566 bool emptyQueue() const { return _list_front == _list_back; }
1568 /// \brief Returns the number of the nodes to be processed.
1570 /// Returns the number of the nodes to be processed in the queue.
1571 int queueSize() const { return _list_back - _list_front; }
1573 /// \brief Executes the algorithm.
1575 /// Executes the algorithm.
1577 /// This method runs the %BFS algorithm from the root node(s)
1578 /// in order to compute the shortest path to each node.
1580 /// The algorithm computes
1581 /// - the shortest path tree (forest),
1582 /// - the distance of each node from the root(s).
1584 /// \pre init() must be called and at least one root node should be added
1585 /// with addSource() before using this function.
1587 /// \note <tt>b.start()</tt> is just a shortcut of the following code.
1589 /// while ( !b.emptyQueue() ) {
1590 /// b.processNextNode();
1594 while ( !emptyQueue() ) processNextNode();
1597 /// \brief Executes the algorithm until the given target node is reached.
1599 /// Executes the algorithm until the given target node is reached.
1601 /// This method runs the %BFS algorithm from the root node(s)
1602 /// in order to compute the shortest path to \c t.
1604 /// The algorithm computes
1605 /// - the shortest path to \c t,
1606 /// - the distance of \c t from the root(s).
1608 /// \pre init() must be called and at least one root node should be
1609 /// added with addSource() before using this function.
1611 /// \note <tt>b.start(t)</tt> is just a shortcut of the following code.
1613 /// bool reach = false;
1614 /// while ( !b.emptyQueue() && !reach ) {
1615 /// b.processNextNode(t, reach);
1618 void start(Node t) {
1620 while ( !emptyQueue() && !reach ) processNextNode(t, reach);
1623 /// \brief Executes the algorithm until a condition is met.
1625 /// Executes the algorithm until a condition is met.
1627 /// This method runs the %BFS algorithm from the root node(s) in
1628 /// order to compute the shortest path to a node \c v with
1629 /// <tt>nm[v]</tt> true, if such a node can be found.
1631 /// \param nm must be a bool (or convertible) node map. The
1632 /// algorithm will stop when it reaches a node \c v with
1633 /// <tt>nm[v]</tt> true.
1635 /// \return The reached node \c v with <tt>nm[v]</tt> true or
1636 /// \c INVALID if no such node was found.
1638 /// \pre init() must be called and at least one root node should be
1639 /// added with addSource() before using this function.
1641 /// \note <tt>b.start(nm)</tt> is just a shortcut of the following code.
1643 /// Node rnode = INVALID;
1644 /// while ( !b.emptyQueue() && rnode == INVALID ) {
1645 /// b.processNextNode(nm, rnode);
1649 template <typename NM>
1650 Node start(const NM &nm) {
1651 Node rnode = INVALID;
1652 while ( !emptyQueue() && rnode == INVALID ) {
1653 processNextNode(nm, rnode);
1658 /// \brief Runs the algorithm from the given source node.
1660 /// This method runs the %BFS algorithm from node \c s
1661 /// in order to compute the shortest path to each node.
1663 /// The algorithm computes
1664 /// - the shortest path tree,
1665 /// - the distance of each node from the root.
1667 /// \note <tt>b.run(s)</tt> is just a shortcut of the following code.
1679 /// \brief Finds the shortest path between \c s and \c t.
1681 /// This method runs the %BFS algorithm from node \c s
1682 /// in order to compute the shortest path to node \c t
1683 /// (it stops searching when \c t is processed).
1685 /// \return \c true if \c t is reachable form \c s.
1687 /// \note Apart from the return value, <tt>b.run(s,t)</tt> is just a
1688 /// shortcut of the following code.
1694 bool run(Node s,Node t) {
1701 /// \brief Runs the algorithm to visit all nodes in the digraph.
1703 /// This method runs the %BFS algorithm in order to
1704 /// compute the shortest path to each node.
1706 /// The algorithm computes
1707 /// - the shortest path tree (forest),
1708 /// - the distance of each node from the root(s).
1710 /// \note <tt>b.run(s)</tt> is just a shortcut of the following code.
1713 /// for (NodeIt n(gr); n != INVALID; ++n) {
1714 /// if (!b.reached(n)) {
1722 for (NodeIt it(*_digraph); it != INVALID; ++it) {
1732 /// \name Query Functions
1733 /// The result of the %BFS algorithm can be obtained using these
1735 /// Either \ref lemon::BfsVisit::run() "run()" or
1736 /// \ref lemon::BfsVisit::start() "start()" must be called before
1740 /// \brief Checks if a node is reachable from the root(s).
1742 /// Returns \c true if \c v is reachable from the root(s).
1743 /// \pre Either \ref run() or \ref start()
1744 /// must be called before using this function.
1745 bool reached(Node v) { return (*_reached)[v]; }
1751 } //END OF NAMESPACE LEMON