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> >
138 ///\ref Exception for uninitialized parameters.
140 ///This error represents problems in the initialization of the
141 ///parameters of the algorithm.
142 class UninitializedParameter : public lemon::UninitializedParameter {
144 virtual const char* what() const throw() {
145 return "lemon::Bfs::UninitializedParameter";
149 ///The type of the digraph the algorithm runs on.
150 typedef typename TR::Digraph Digraph;
152 ///\brief The type of the map that stores the predecessor arcs of the
154 typedef typename TR::PredMap PredMap;
155 ///The type of the map that stores the distances of the nodes.
156 typedef typename TR::DistMap DistMap;
157 ///The type of the map that indicates which nodes are reached.
158 typedef typename TR::ReachedMap ReachedMap;
159 ///The type of the map that indicates which nodes are processed.
160 typedef typename TR::ProcessedMap ProcessedMap;
161 ///The type of the paths.
162 typedef PredMapPath<Digraph, PredMap> Path;
169 typedef typename Digraph::Node Node;
170 typedef typename Digraph::NodeIt NodeIt;
171 typedef typename Digraph::Arc Arc;
172 typedef typename Digraph::OutArcIt OutArcIt;
174 //Pointer to the underlying digraph.
176 //Pointer to the map of predecessor arcs.
178 //Indicates if _pred is locally allocated (true) or not.
180 //Pointer to the map of distances.
182 //Indicates if _dist is locally allocated (true) or not.
184 //Pointer to the map of reached status of the nodes.
185 ReachedMap *_reached;
186 //Indicates if _reached is locally allocated (true) or not.
188 //Pointer to the map of processed status of the nodes.
189 ProcessedMap *_processed;
190 //Indicates if _processed is locally allocated (true) or not.
191 bool local_processed;
193 std::vector<typename Digraph::Node> _queue;
194 int _queue_head,_queue_tail,_queue_next_dist;
197 //Creates the maps if necessary.
202 _pred = Traits::createPredMap(*G);
206 _dist = Traits::createDistMap(*G);
209 local_reached = true;
210 _reached = Traits::createReachedMap(*G);
213 local_processed = true;
214 _processed = Traits::createProcessedMap(*G);
226 ///\name Named template parameters
231 struct SetPredMapTraits : public Traits {
233 static PredMap *createPredMap(const Digraph &)
235 throw UninitializedParameter();
238 ///\brief \ref named-templ-param "Named parameter" for setting
239 ///\ref PredMap type.
241 ///\ref named-templ-param "Named parameter" for setting
242 ///\ref PredMap type.
244 struct SetPredMap : public Bfs< Digraph, SetPredMapTraits<T> > {
245 typedef Bfs< Digraph, SetPredMapTraits<T> > Create;
249 struct SetDistMapTraits : public Traits {
251 static DistMap *createDistMap(const Digraph &)
253 throw UninitializedParameter();
256 ///\brief \ref named-templ-param "Named parameter" for setting
257 ///\ref DistMap type.
259 ///\ref named-templ-param "Named parameter" for setting
260 ///\ref DistMap type.
262 struct SetDistMap : public Bfs< Digraph, SetDistMapTraits<T> > {
263 typedef Bfs< Digraph, SetDistMapTraits<T> > Create;
267 struct SetReachedMapTraits : public Traits {
268 typedef T ReachedMap;
269 static ReachedMap *createReachedMap(const Digraph &)
271 throw UninitializedParameter();
274 ///\brief \ref named-templ-param "Named parameter" for setting
275 ///\ref ReachedMap type.
277 ///\ref named-templ-param "Named parameter" for setting
278 ///\ref ReachedMap type.
280 struct SetReachedMap : public Bfs< Digraph, SetReachedMapTraits<T> > {
281 typedef Bfs< Digraph, SetReachedMapTraits<T> > Create;
285 struct SetProcessedMapTraits : public Traits {
286 typedef T ProcessedMap;
287 static ProcessedMap *createProcessedMap(const Digraph &)
289 throw UninitializedParameter();
292 ///\brief \ref named-templ-param "Named parameter" for setting
293 ///\ref ProcessedMap type.
295 ///\ref named-templ-param "Named parameter" for setting
296 ///\ref ProcessedMap type.
298 struct SetProcessedMap : public Bfs< Digraph, SetProcessedMapTraits<T> > {
299 typedef Bfs< Digraph, SetProcessedMapTraits<T> > Create;
302 struct SetStandardProcessedMapTraits : public Traits {
303 typedef typename Digraph::template NodeMap<bool> ProcessedMap;
304 static ProcessedMap *createProcessedMap(const Digraph &g)
306 return new ProcessedMap(g);
309 ///\brief \ref named-templ-param "Named parameter" for setting
310 ///\ref ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
312 ///\ref named-templ-param "Named parameter" for setting
313 ///\ref ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
314 ///If you don't set it explicitly, it will be automatically allocated.
315 struct SetStandardProcessedMap :
316 public Bfs< Digraph, SetStandardProcessedMapTraits > {
317 typedef Bfs< Digraph, SetStandardProcessedMapTraits > Create;
327 ///\param g The digraph the algorithm runs on.
328 Bfs(const Digraph &g) :
330 _pred(NULL), local_pred(false),
331 _dist(NULL), local_dist(false),
332 _reached(NULL), local_reached(false),
333 _processed(NULL), local_processed(false)
339 if(local_pred) delete _pred;
340 if(local_dist) delete _dist;
341 if(local_reached) delete _reached;
342 if(local_processed) delete _processed;
345 ///Sets the map that stores the predecessor arcs.
347 ///Sets the map that stores the predecessor arcs.
348 ///If you don't use this function before calling \ref run(),
349 ///it will allocate one. The destructor deallocates this
350 ///automatically allocated map, of course.
351 ///\return <tt> (*this) </tt>
352 Bfs &predMap(PredMap &m)
362 ///Sets the map that indicates which nodes are reached.
364 ///Sets the map that indicates which nodes are reached.
365 ///If you don't use this function before calling \ref run(),
366 ///it will allocate one. The destructor deallocates this
367 ///automatically allocated map, of course.
368 ///\return <tt> (*this) </tt>
369 Bfs &reachedMap(ReachedMap &m)
379 ///Sets the map that indicates which nodes are processed.
381 ///Sets the map that indicates which nodes are processed.
382 ///If you don't use this function before calling \ref run(),
383 ///it will allocate one. The destructor deallocates this
384 ///automatically allocated map, of course.
385 ///\return <tt> (*this) </tt>
386 Bfs &processedMap(ProcessedMap &m)
388 if(local_processed) {
390 local_processed=false;
396 ///Sets the map that stores the distances of the nodes.
398 ///Sets the map that stores the distances of the nodes calculated by
400 ///If you don't use this function before calling \ref run(),
401 ///it will allocate one. The destructor deallocates this
402 ///automatically allocated map, of course.
403 ///\return <tt> (*this) </tt>
404 Bfs &distMap(DistMap &m)
416 ///\name Execution control
417 ///The simplest way to execute the algorithm is to use
418 ///one of the member functions called \ref lemon::Bfs::run() "run()".
420 ///If you need more control on the execution, first you must call
421 ///\ref lemon::Bfs::init() "init()", then you can add several source
422 ///nodes with \ref lemon::Bfs::addSource() "addSource()".
423 ///Finally \ref lemon::Bfs::start() "start()" will perform the
424 ///actual path computation.
428 ///Initializes the internal data structures.
430 ///Initializes the internal data structures.
435 _queue.resize(countNodes(*G));
436 _queue_head=_queue_tail=0;
438 for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
439 _pred->set(u,INVALID);
440 _reached->set(u,false);
441 _processed->set(u,false);
445 ///Adds a new source node.
447 ///Adds a new source node to the set of nodes to be processed.
449 void addSource(Node s)
453 _reached->set(s,true);
454 _pred->set(s,INVALID);
456 _queue[_queue_head++]=s;
457 _queue_next_dist=_queue_head;
461 ///Processes the next node.
463 ///Processes the next node.
465 ///\return The processed node.
467 ///\pre The queue must not be empty.
468 Node processNextNode()
470 if(_queue_tail==_queue_next_dist) {
472 _queue_next_dist=_queue_head;
474 Node n=_queue[_queue_tail++];
475 _processed->set(n,true);
477 for(OutArcIt e(*G,n);e!=INVALID;++e)
478 if(!(*_reached)[m=G->target(e)]) {
479 _queue[_queue_head++]=m;
480 _reached->set(m,true);
482 _dist->set(m,_curr_dist);
487 ///Processes the next node.
489 ///Processes the next node and checks if the given target node
490 ///is reached. If the target node is reachable from the processed
491 ///node, then the \c reach parameter will be set to \c true.
493 ///\param target The target node.
494 ///\retval reach Indicates if the target node is reached.
495 ///It should be initially \c false.
497 ///\return The processed node.
499 ///\pre The queue must not be empty.
500 Node processNextNode(Node target, bool& reach)
502 if(_queue_tail==_queue_next_dist) {
504 _queue_next_dist=_queue_head;
506 Node n=_queue[_queue_tail++];
507 _processed->set(n,true);
509 for(OutArcIt e(*G,n);e!=INVALID;++e)
510 if(!(*_reached)[m=G->target(e)]) {
511 _queue[_queue_head++]=m;
512 _reached->set(m,true);
514 _dist->set(m,_curr_dist);
515 reach = reach || (target == m);
520 ///Processes the next node.
522 ///Processes the next node and checks if at least one of reached
523 ///nodes has \c true value in the \c nm node map. If one node
524 ///with \c true value is reachable from the processed node, then the
525 ///\c rnode parameter will be set to the first of such nodes.
527 ///\param nm A \c bool (or convertible) node map that indicates the
529 ///\retval rnode The reached target node.
530 ///It should be initially \c INVALID.
532 ///\return The processed node.
534 ///\pre The queue must not be empty.
536 Node processNextNode(const NM& nm, Node& rnode)
538 if(_queue_tail==_queue_next_dist) {
540 _queue_next_dist=_queue_head;
542 Node n=_queue[_queue_tail++];
543 _processed->set(n,true);
545 for(OutArcIt e(*G,n);e!=INVALID;++e)
546 if(!(*_reached)[m=G->target(e)]) {
547 _queue[_queue_head++]=m;
548 _reached->set(m,true);
550 _dist->set(m,_curr_dist);
551 if (nm[m] && rnode == INVALID) rnode = m;
556 ///The next node to be processed.
558 ///Returns the next node to be processed or \c INVALID if the queue
560 Node nextNode() const
562 return _queue_tail<_queue_head?_queue[_queue_tail]:INVALID;
565 ///\brief Returns \c false if there are nodes
568 ///Returns \c false if there are nodes
569 ///to be processed in the queue.
570 bool emptyQueue() const { return _queue_tail==_queue_head; }
572 ///Returns the number of the nodes to be processed.
574 ///Returns the number of the nodes to be processed in the queue.
575 int queueSize() const { return _queue_head-_queue_tail; }
577 ///Executes the algorithm.
579 ///Executes the algorithm.
581 ///This method runs the %BFS algorithm from the root node(s)
582 ///in order to compute the shortest path to each node.
584 ///The algorithm computes
585 ///- the shortest path tree (forest),
586 ///- the distance of each node from the root(s).
588 ///\pre init() must be called and at least one root node should be
589 ///added with addSource() before using this function.
591 ///\note <tt>b.start()</tt> is just a shortcut of the following code.
593 /// while ( !b.emptyQueue() ) {
594 /// b.processNextNode();
599 while ( !emptyQueue() ) processNextNode();
602 ///Executes the algorithm until the given target node is reached.
604 ///Executes the algorithm until the given target node is reached.
606 ///This method runs the %BFS algorithm from the root node(s)
607 ///in order to compute the shortest path to \c dest.
609 ///The algorithm computes
610 ///- the shortest path to \c dest,
611 ///- the distance of \c dest from the root(s).
613 ///\pre init() must be called and at least one root node should be
614 ///added with addSource() before using this function.
616 ///\note <tt>b.start(t)</tt> is just a shortcut of the following code.
618 /// bool reach = false;
619 /// while ( !b.emptyQueue() && !reach ) {
620 /// b.processNextNode(t, reach);
623 void start(Node dest)
626 while ( !emptyQueue() && !reach ) processNextNode(dest, reach);
629 ///Executes the algorithm until a condition is met.
631 ///Executes the algorithm until a condition is met.
633 ///This method runs the %BFS algorithm from the root node(s) in
634 ///order to compute the shortest path to a node \c v with
635 /// <tt>nm[v]</tt> true, if such a node can be found.
637 ///\param nm A \c bool (or convertible) node map. The algorithm
638 ///will stop when it reaches a node \c v with <tt>nm[v]</tt> true.
640 ///\return The reached node \c v with <tt>nm[v]</tt> true or
641 ///\c INVALID if no such node was found.
643 ///\pre init() must be called and at least one root node should be
644 ///added with addSource() before using this function.
646 ///\note <tt>b.start(nm)</tt> is just a shortcut of the following code.
648 /// Node rnode = INVALID;
649 /// while ( !b.emptyQueue() && rnode == INVALID ) {
650 /// b.processNextNode(nm, rnode);
654 template<class NodeBoolMap>
655 Node start(const NodeBoolMap &nm)
657 Node rnode = INVALID;
658 while ( !emptyQueue() && rnode == INVALID ) {
659 processNextNode(nm, rnode);
664 ///Runs the algorithm from the given node.
666 ///This method runs the %BFS algorithm from node \c s
667 ///in order to compute the shortest path to each node.
669 ///The algorithm computes
670 ///- the shortest path tree,
671 ///- the distance of each node from the root.
673 ///\note <tt>b.run(s)</tt> is just a shortcut of the following code.
685 ///Finds the shortest path between \c s and \c t.
687 ///This method runs the %BFS algorithm from node \c s
688 ///in order to compute the shortest path to \c t.
690 ///\return The length of the shortest <tt>s</tt>--<tt>t</tt> path,
691 ///if \c t is reachable form \c s, \c 0 otherwise.
693 ///\note Apart from the return value, <tt>b.run(s,t)</tt> is just a
694 ///shortcut of the following code.
700 int run(Node s,Node t) {
704 return reached(t) ? _curr_dist : 0;
707 ///Runs the algorithm to visit all nodes in the digraph.
709 ///This method runs the %BFS algorithm in order to
710 ///compute the shortest path to each node.
712 ///The algorithm computes
713 ///- the shortest path tree (forest),
714 ///- the distance of each node from the root(s).
716 ///\note <tt>b.run(s)</tt> is just a shortcut of the following code.
719 /// for (NodeIt n(gr); n != INVALID; ++n) {
720 /// if (!b.reached(n)) {
728 for (NodeIt n(*G); n != INVALID; ++n) {
738 ///\name Query Functions
739 ///The result of the %BFS algorithm can be obtained using these
741 ///Either \ref lemon::Bfs::run() "run()" or \ref lemon::Bfs::start()
742 ///"start()" must be called before using them.
746 ///The shortest path to a node.
748 ///Returns the shortest path to a node.
750 ///\warning \c t should be reachable from the root(s).
752 ///\pre Either \ref run() or \ref start() must be called before
753 ///using this function.
754 Path path(Node t) const { return Path(*G, *_pred, t); }
756 ///The distance of a node from the root(s).
758 ///Returns the distance of a node from the root(s).
760 ///\warning If node \c v is not reachable from the root(s), then
761 ///the return value of this function is undefined.
763 ///\pre Either \ref run() or \ref start() must be called before
764 ///using this function.
765 int dist(Node v) const { return (*_dist)[v]; }
767 ///Returns the 'previous arc' of the shortest path tree for a node.
769 ///This function returns the 'previous arc' of the shortest path
770 ///tree for the node \c v, i.e. it returns the last arc of a
771 ///shortest path from the root(s) to \c v. It is \c INVALID if \c v
772 ///is not reachable from the root(s) or if \c v is a root.
774 ///The shortest path tree used here is equal to the shortest path
775 ///tree used in \ref predNode().
777 ///\pre Either \ref run() or \ref start() must be called before
778 ///using this function.
779 Arc predArc(Node v) const { return (*_pred)[v];}
781 ///Returns the 'previous node' of the shortest path tree for a node.
783 ///This function returns the 'previous node' of the shortest path
784 ///tree for the node \c v, i.e. it returns the last but one node
785 ///from a shortest path from the root(s) to \c v. It is \c INVALID
786 ///if \c v is not reachable from the root(s) or if \c v is a root.
788 ///The shortest path tree used here is equal to the shortest path
789 ///tree used in \ref predArc().
791 ///\pre Either \ref run() or \ref start() must be called before
792 ///using this function.
793 Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
794 G->source((*_pred)[v]); }
796 ///\brief Returns a const reference to the node map that stores the
797 /// distances of the nodes.
799 ///Returns a const reference to the node map that stores the distances
800 ///of the nodes calculated by the algorithm.
802 ///\pre Either \ref run() or \ref init()
803 ///must be called before using this function.
804 const DistMap &distMap() const { return *_dist;}
806 ///\brief Returns a const reference to the node map that stores the
809 ///Returns a const reference to the node map that stores the predecessor
810 ///arcs, which form the shortest path tree.
812 ///\pre Either \ref run() or \ref init()
813 ///must be called before using this function.
814 const PredMap &predMap() const { return *_pred;}
816 ///Checks if a node is reachable from the root(s).
818 ///Returns \c true if \c v is reachable from the root(s).
819 ///\pre Either \ref run() or \ref start()
820 ///must be called before using this function.
821 bool reached(Node v) const { return (*_reached)[v]; }
826 ///Default traits class of bfs() function.
828 ///Default traits class of bfs() function.
829 ///\tparam GR Digraph type.
831 struct BfsWizardDefaultTraits
833 ///The type of the digraph the algorithm runs on.
836 ///\brief The type of the map that stores the predecessor
837 ///arcs of the shortest paths.
839 ///The type of the map that stores the predecessor
840 ///arcs of the shortest paths.
841 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
842 typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
843 ///Instantiates a \ref PredMap.
845 ///This function instantiates a \ref PredMap.
846 ///\param g is the digraph, to which we would like to define the
848 static PredMap *createPredMap(const Digraph &g)
850 return new PredMap(g);
853 ///The type of the map that indicates which nodes are processed.
855 ///The type of the map that indicates which nodes are processed.
856 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
857 ///By default it is a NullMap.
858 typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
859 ///Instantiates a \ref ProcessedMap.
861 ///This function instantiates a \ref ProcessedMap.
862 ///\param g is the digraph, to which
863 ///we would like to define the \ref ProcessedMap.
865 static ProcessedMap *createProcessedMap(const Digraph &g)
867 static ProcessedMap *createProcessedMap(const Digraph &)
870 return new ProcessedMap();
873 ///The type of the map that indicates which nodes are reached.
875 ///The type of the map that indicates which nodes are reached.
876 ///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
877 typedef typename Digraph::template NodeMap<bool> ReachedMap;
878 ///Instantiates a \ref ReachedMap.
880 ///This function instantiates a \ref ReachedMap.
881 ///\param g is the digraph, to which
882 ///we would like to define the \ref ReachedMap.
883 static ReachedMap *createReachedMap(const Digraph &g)
885 return new ReachedMap(g);
888 ///The type of the map that stores the distances of the nodes.
890 ///The type of the map that stores the distances of the nodes.
891 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
892 typedef typename Digraph::template NodeMap<int> DistMap;
893 ///Instantiates a \ref DistMap.
895 ///This function instantiates a \ref DistMap.
896 ///\param g is the digraph, to which we would like to define
898 static DistMap *createDistMap(const Digraph &g)
900 return new DistMap(g);
903 ///The type of the shortest paths.
905 ///The type of the shortest paths.
906 ///It must meet the \ref concepts::Path "Path" concept.
907 typedef lemon::Path<Digraph> Path;
910 /// Default traits class used by \ref BfsWizard
912 /// To make it easier to use Bfs algorithm
913 /// we have created a wizard class.
914 /// This \ref BfsWizard class needs default traits,
915 /// as well as the \ref Bfs class.
916 /// The \ref BfsWizardBase is a class to be the default traits of the
917 /// \ref BfsWizard class.
919 class BfsWizardBase : public BfsWizardDefaultTraits<GR>
922 typedef BfsWizardDefaultTraits<GR> Base;
924 //The type of the nodes in the digraph.
925 typedef typename Base::Digraph::Node Node;
927 //Pointer to the digraph the algorithm runs on.
929 //Pointer to the map of reached nodes.
931 //Pointer to the map of processed nodes.
933 //Pointer to the map of predecessors arcs.
935 //Pointer to the map of distances.
937 //Pointer to the shortest path to the target node.
939 //Pointer to the distance of the target node.
945 /// This constructor does not require parameters, therefore it initiates
946 /// all of the attributes to \c 0.
947 BfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0),
948 _dist(0), _path(0), _di(0) {}
952 /// This constructor requires one parameter,
953 /// others are initiated to \c 0.
954 /// \param g The digraph the algorithm runs on.
955 BfsWizardBase(const GR &g) :
956 _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
957 _reached(0), _processed(0), _pred(0), _dist(0), _path(0), _di(0) {}
961 /// Auxiliary class for the function-type interface of BFS algorithm.
963 /// This auxiliary class is created to implement the
964 /// \ref bfs() "function-type interface" of \ref Bfs algorithm.
965 /// It does not have own \ref run() method, it uses the functions
966 /// and features of the plain \ref Bfs.
968 /// This class should only be used through the \ref bfs() function,
969 /// which makes it easier to use the algorithm.
971 class BfsWizard : public TR
975 ///The type of the digraph the algorithm runs on.
976 typedef typename TR::Digraph Digraph;
978 typedef typename Digraph::Node Node;
979 typedef typename Digraph::NodeIt NodeIt;
980 typedef typename Digraph::Arc Arc;
981 typedef typename Digraph::OutArcIt OutArcIt;
983 ///\brief The type of the map that stores the predecessor
984 ///arcs of the shortest paths.
985 typedef typename TR::PredMap PredMap;
986 ///\brief The type of the map that stores the distances of the nodes.
987 typedef typename TR::DistMap DistMap;
988 ///\brief The type of the map that indicates which nodes are reached.
989 typedef typename TR::ReachedMap ReachedMap;
990 ///\brief The type of the map that indicates which nodes are processed.
991 typedef typename TR::ProcessedMap ProcessedMap;
992 ///The type of the shortest paths
993 typedef typename TR::Path Path;
998 BfsWizard() : TR() {}
1000 /// Constructor that requires parameters.
1002 /// Constructor that requires parameters.
1003 /// These parameters will be the default values for the traits class.
1004 /// \param g The digraph the algorithm runs on.
1005 BfsWizard(const Digraph &g) :
1009 BfsWizard(const TR &b) : TR(b) {}
1013 ///Runs BFS algorithm from the given source node.
1015 ///This method runs BFS algorithm from node \c s
1016 ///in order to compute the shortest path to each node.
1019 Bfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
1021 alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1023 alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1025 alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
1026 if (Base::_processed)
1027 alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1034 ///Finds the shortest path between \c s and \c t.
1036 ///This method runs BFS algorithm from node \c s
1037 ///in order to compute the shortest path to node \c t
1038 ///(it stops searching when \c t is processed).
1040 ///\return \c true if \c t is reachable form \c s.
1041 bool run(Node s, Node t)
1043 if (s==INVALID || t==INVALID) throw UninitializedParameter();
1044 Bfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
1046 alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1048 alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1050 alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
1051 if (Base::_processed)
1052 alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1055 *reinterpret_cast<Path*>(Base::_path) = alg.path(t);
1057 *Base::_di = alg.dist(t);
1058 return alg.reached(t);
1061 ///Runs BFS algorithm to visit all nodes in the digraph.
1063 ///This method runs BFS algorithm in order to compute
1064 ///the shortest path to each node.
1071 struct SetPredMapBase : public Base {
1073 static PredMap *createPredMap(const Digraph &) { return 0; };
1074 SetPredMapBase(const TR &b) : TR(b) {}
1076 ///\brief \ref named-func-param "Named parameter"
1077 ///for setting \ref PredMap object.
1079 ///\ref named-func-param "Named parameter"
1080 ///for setting \ref PredMap object.
1082 BfsWizard<SetPredMapBase<T> > predMap(const T &t)
1084 Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1085 return BfsWizard<SetPredMapBase<T> >(*this);
1089 struct SetReachedMapBase : public Base {
1090 typedef T ReachedMap;
1091 static ReachedMap *createReachedMap(const Digraph &) { return 0; };
1092 SetReachedMapBase(const TR &b) : TR(b) {}
1094 ///\brief \ref named-func-param "Named parameter"
1095 ///for setting \ref ReachedMap object.
1097 /// \ref named-func-param "Named parameter"
1098 ///for setting \ref ReachedMap object.
1100 BfsWizard<SetReachedMapBase<T> > reachedMap(const T &t)
1102 Base::_reached=reinterpret_cast<void*>(const_cast<T*>(&t));
1103 return BfsWizard<SetReachedMapBase<T> >(*this);
1107 struct SetDistMapBase : public Base {
1109 static DistMap *createDistMap(const Digraph &) { return 0; };
1110 SetDistMapBase(const TR &b) : TR(b) {}
1112 ///\brief \ref named-func-param "Named parameter"
1113 ///for setting \ref DistMap object.
1115 /// \ref named-func-param "Named parameter"
1116 ///for setting \ref DistMap object.
1118 BfsWizard<SetDistMapBase<T> > distMap(const T &t)
1120 Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1121 return BfsWizard<SetDistMapBase<T> >(*this);
1125 struct SetProcessedMapBase : public Base {
1126 typedef T ProcessedMap;
1127 static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
1128 SetProcessedMapBase(const TR &b) : TR(b) {}
1130 ///\brief \ref named-func-param "Named parameter"
1131 ///for setting \ref ProcessedMap object.
1133 /// \ref named-func-param "Named parameter"
1134 ///for setting \ref ProcessedMap object.
1136 BfsWizard<SetProcessedMapBase<T> > processedMap(const T &t)
1138 Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1139 return BfsWizard<SetProcessedMapBase<T> >(*this);
1143 struct SetPathBase : public Base {
1145 SetPathBase(const TR &b) : TR(b) {}
1147 ///\brief \ref named-func-param "Named parameter"
1148 ///for getting the shortest path to the target node.
1150 ///\ref named-func-param "Named parameter"
1151 ///for getting the shortest path to the target node.
1153 BfsWizard<SetPathBase<T> > path(const T &t)
1155 Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t));
1156 return BfsWizard<SetPathBase<T> >(*this);
1159 ///\brief \ref named-func-param "Named parameter"
1160 ///for getting the distance of the target node.
1162 ///\ref named-func-param "Named parameter"
1163 ///for getting the distance of the target node.
1164 BfsWizard dist(const int &d)
1166 Base::_di=const_cast<int*>(&d);
1172 ///Function-type interface for BFS algorithm.
1175 ///Function-type interface for BFS algorithm.
1177 ///This function also has several \ref named-func-param "named parameters",
1178 ///they are declared as the members of class \ref BfsWizard.
1179 ///The following examples show how to use these parameters.
1181 /// // Compute shortest path from node s to each node
1182 /// bfs(g).predMap(preds).distMap(dists).run(s);
1184 /// // Compute shortest path from s to t
1185 /// bool reached = bfs(g).path(p).dist(d).run(s,t);
1187 ///\warning Don't forget to put the \ref BfsWizard::run() "run()"
1188 ///to the end of the parameter list.
1192 BfsWizard<BfsWizardBase<GR> >
1193 bfs(const GR &digraph)
1195 return BfsWizard<BfsWizardBase<GR> >(digraph);
1199 /// \brief Visitor class for BFS.
1201 /// This class defines the interface of the BfsVisit events, and
1202 /// it could be the base of a real visitor class.
1203 template <typename _Digraph>
1205 typedef _Digraph Digraph;
1206 typedef typename Digraph::Arc Arc;
1207 typedef typename Digraph::Node Node;
1208 /// \brief Called for the source node(s) of the BFS.
1210 /// This function is called for the source node(s) of the BFS.
1211 void start(const Node& node) {}
1212 /// \brief Called when a node is reached first time.
1214 /// This function is called when a node is reached first time.
1215 void reach(const Node& node) {}
1216 /// \brief Called when a node is processed.
1218 /// This function is called when a node is processed.
1219 void process(const Node& node) {}
1220 /// \brief Called when an arc reaches a new node.
1222 /// This function is called when the BFS finds an arc whose target node
1223 /// is not reached yet.
1224 void discover(const Arc& arc) {}
1225 /// \brief Called when an arc is examined but its target node is
1226 /// already discovered.
1228 /// This function is called when an arc is examined but its target node is
1229 /// already discovered.
1230 void examine(const Arc& arc) {}
1233 template <typename _Digraph>
1235 typedef _Digraph Digraph;
1236 typedef typename Digraph::Arc Arc;
1237 typedef typename Digraph::Node Node;
1238 void start(const Node&) {}
1239 void reach(const Node&) {}
1240 void process(const Node&) {}
1241 void discover(const Arc&) {}
1242 void examine(const Arc&) {}
1244 template <typename _Visitor>
1245 struct Constraints {
1246 void constraints() {
1249 visitor.start(node);
1250 visitor.reach(node);
1251 visitor.process(node);
1252 visitor.discover(arc);
1253 visitor.examine(arc);
1260 /// \brief Default traits class of BfsVisit class.
1262 /// Default traits class of BfsVisit class.
1263 /// \tparam _Digraph The type of the digraph the algorithm runs on.
1264 template<class _Digraph>
1265 struct BfsVisitDefaultTraits {
1267 /// \brief The type of the digraph the algorithm runs on.
1268 typedef _Digraph Digraph;
1270 /// \brief The type of the map that indicates which nodes are reached.
1272 /// The type of the map that indicates which nodes are reached.
1273 /// It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
1274 typedef typename Digraph::template NodeMap<bool> ReachedMap;
1276 /// \brief Instantiates a \ref ReachedMap.
1278 /// This function instantiates a \ref ReachedMap.
1279 /// \param digraph is the digraph, to which
1280 /// we would like to define the \ref ReachedMap.
1281 static ReachedMap *createReachedMap(const Digraph &digraph) {
1282 return new ReachedMap(digraph);
1289 /// \brief %BFS algorithm class with visitor interface.
1291 /// This class provides an efficient implementation of the %BFS algorithm
1292 /// with visitor interface.
1294 /// The %BfsVisit class provides an alternative interface to the Bfs
1295 /// class. It works with callback mechanism, the BfsVisit object calls
1296 /// the member functions of the \c Visitor class on every BFS event.
1298 /// This interface of the BFS algorithm should be used in special cases
1299 /// when extra actions have to be performed in connection with certain
1300 /// events of the BFS algorithm. Otherwise consider to use Bfs or bfs()
1303 /// \tparam _Digraph The type of the digraph the algorithm runs on.
1304 /// The default value is
1305 /// \ref ListDigraph. The value of _Digraph is not used directly by
1306 /// \ref BfsVisit, it is only passed to \ref BfsVisitDefaultTraits.
1307 /// \tparam _Visitor The Visitor type that is used by the algorithm.
1308 /// \ref BfsVisitor "BfsVisitor<_Digraph>" is an empty visitor, which
1309 /// does not observe the BFS events. If you want to observe the BFS
1310 /// events, you should implement your own visitor class.
1311 /// \tparam _Traits Traits class to set various data types used by the
1312 /// algorithm. The default traits class is
1313 /// \ref BfsVisitDefaultTraits "BfsVisitDefaultTraits<_Digraph>".
1314 /// See \ref BfsVisitDefaultTraits for the documentation of
1315 /// a BFS visit traits class.
1317 template <typename _Digraph, typename _Visitor, typename _Traits>
1319 template <typename _Digraph = ListDigraph,
1320 typename _Visitor = BfsVisitor<_Digraph>,
1321 typename _Traits = BfsDefaultTraits<_Digraph> >
1326 /// \brief \ref Exception for uninitialized parameters.
1328 /// This error represents problems in the initialization
1329 /// of the parameters of the algorithm.
1330 class UninitializedParameter : public lemon::UninitializedParameter {
1332 virtual const char* what() const throw()
1334 return "lemon::BfsVisit::UninitializedParameter";
1338 ///The traits class.
1339 typedef _Traits Traits;
1341 ///The type of the digraph the algorithm runs on.
1342 typedef typename Traits::Digraph Digraph;
1344 ///The visitor type used by the algorithm.
1345 typedef _Visitor Visitor;
1347 ///The type of the map that indicates which nodes are reached.
1348 typedef typename Traits::ReachedMap ReachedMap;
1352 typedef typename Digraph::Node Node;
1353 typedef typename Digraph::NodeIt NodeIt;
1354 typedef typename Digraph::Arc Arc;
1355 typedef typename Digraph::OutArcIt OutArcIt;
1357 //Pointer to the underlying digraph.
1358 const Digraph *_digraph;
1359 //Pointer to the visitor object.
1361 //Pointer to the map of reached status of the nodes.
1362 ReachedMap *_reached;
1363 //Indicates if _reached is locally allocated (true) or not.
1366 std::vector<typename Digraph::Node> _list;
1367 int _list_front, _list_back;
1369 //Creates the maps if necessary.
1370 void create_maps() {
1372 local_reached = true;
1373 _reached = Traits::createReachedMap(*_digraph);
1383 typedef BfsVisit Create;
1385 /// \name Named template parameters
1389 struct SetReachedMapTraits : public Traits {
1390 typedef T ReachedMap;
1391 static ReachedMap *createReachedMap(const Digraph &digraph) {
1392 throw UninitializedParameter();
1395 /// \brief \ref named-templ-param "Named parameter" for setting
1396 /// ReachedMap type.
1398 /// \ref named-templ-param "Named parameter" for setting ReachedMap type.
1400 struct SetReachedMap : public BfsVisit< Digraph, Visitor,
1401 SetReachedMapTraits<T> > {
1402 typedef BfsVisit< Digraph, Visitor, SetReachedMapTraits<T> > Create;
1408 /// \brief Constructor.
1412 /// \param digraph The digraph the algorithm runs on.
1413 /// \param visitor The visitor object of the algorithm.
1414 BfsVisit(const Digraph& digraph, Visitor& visitor)
1415 : _digraph(&digraph), _visitor(&visitor),
1416 _reached(0), local_reached(false) {}
1418 /// \brief Destructor.
1420 if(local_reached) delete _reached;
1423 /// \brief Sets the map that indicates which nodes are reached.
1425 /// Sets the map that indicates which nodes are reached.
1426 /// If you don't use this function before calling \ref run(),
1427 /// it will allocate one. The destructor deallocates this
1428 /// automatically allocated map, of course.
1429 /// \return <tt> (*this) </tt>
1430 BfsVisit &reachedMap(ReachedMap &m) {
1433 local_reached = false;
1441 /// \name Execution control
1442 /// The simplest way to execute the algorithm is to use
1443 /// one of the member functions called \ref lemon::BfsVisit::run()
1446 /// If you need more control on the execution, first you must call
1447 /// \ref lemon::BfsVisit::init() "init()", then you can add several
1448 /// source nodes with \ref lemon::BfsVisit::addSource() "addSource()".
1449 /// Finally \ref lemon::BfsVisit::start() "start()" will perform the
1450 /// actual path computation.
1454 /// \brief Initializes the internal data structures.
1456 /// Initializes the internal data structures.
1459 _list.resize(countNodes(*_digraph));
1460 _list_front = _list_back = -1;
1461 for (NodeIt u(*_digraph) ; u != INVALID ; ++u) {
1462 _reached->set(u, false);
1466 /// \brief Adds a new source node.
1468 /// Adds a new source node to the set of nodes to be processed.
1469 void addSource(Node s) {
1470 if(!(*_reached)[s]) {
1471 _reached->set(s,true);
1474 _list[++_list_back] = s;
1478 /// \brief Processes the next node.
1480 /// Processes the next node.
1482 /// \return The processed node.
1484 /// \pre The queue must not be empty.
1485 Node processNextNode() {
1486 Node n = _list[++_list_front];
1487 _visitor->process(n);
1489 for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1490 Node m = _digraph->target(e);
1491 if (!(*_reached)[m]) {
1492 _visitor->discover(e);
1494 _reached->set(m, true);
1495 _list[++_list_back] = m;
1497 _visitor->examine(e);
1503 /// \brief Processes the next node.
1505 /// Processes the next node and checks if the given target node
1506 /// is reached. If the target node is reachable from the processed
1507 /// node, then the \c reach parameter will be set to \c true.
1509 /// \param target The target node.
1510 /// \retval reach Indicates if the target node is reached.
1511 /// It should be initially \c false.
1513 /// \return The processed node.
1515 /// \pre The queue must not be empty.
1516 Node processNextNode(Node target, bool& reach) {
1517 Node n = _list[++_list_front];
1518 _visitor->process(n);
1520 for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1521 Node m = _digraph->target(e);
1522 if (!(*_reached)[m]) {
1523 _visitor->discover(e);
1525 _reached->set(m, true);
1526 _list[++_list_back] = m;
1527 reach = reach || (target == m);
1529 _visitor->examine(e);
1535 /// \brief Processes the next node.
1537 /// Processes the next node and checks if at least one of reached
1538 /// nodes has \c true value in the \c nm node map. If one node
1539 /// with \c true value is reachable from the processed node, then the
1540 /// \c rnode parameter will be set to the first of such nodes.
1542 /// \param nm A \c bool (or convertible) node map that indicates the
1543 /// possible targets.
1544 /// \retval rnode The reached target node.
1545 /// It should be initially \c INVALID.
1547 /// \return The processed node.
1549 /// \pre The queue must not be empty.
1550 template <typename NM>
1551 Node processNextNode(const NM& nm, Node& rnode) {
1552 Node n = _list[++_list_front];
1553 _visitor->process(n);
1555 for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1556 Node m = _digraph->target(e);
1557 if (!(*_reached)[m]) {
1558 _visitor->discover(e);
1560 _reached->set(m, true);
1561 _list[++_list_back] = m;
1562 if (nm[m] && rnode == INVALID) rnode = m;
1564 _visitor->examine(e);
1570 /// \brief The next node to be processed.
1572 /// Returns the next node to be processed or \c INVALID if the queue
1574 Node nextNode() const {
1575 return _list_front != _list_back ? _list[_list_front + 1] : INVALID;
1578 /// \brief Returns \c false if there are nodes
1579 /// to be processed.
1581 /// Returns \c false if there are nodes
1582 /// to be processed in the queue.
1583 bool emptyQueue() const { return _list_front == _list_back; }
1585 /// \brief Returns the number of the nodes to be processed.
1587 /// Returns the number of the nodes to be processed in the queue.
1588 int queueSize() const { return _list_back - _list_front; }
1590 /// \brief Executes the algorithm.
1592 /// Executes the algorithm.
1594 /// This method runs the %BFS algorithm from the root node(s)
1595 /// in order to compute the shortest path to each node.
1597 /// The algorithm computes
1598 /// - the shortest path tree (forest),
1599 /// - the distance of each node from the root(s).
1601 /// \pre init() must be called and at least one root node should be added
1602 /// with addSource() before using this function.
1604 /// \note <tt>b.start()</tt> is just a shortcut of the following code.
1606 /// while ( !b.emptyQueue() ) {
1607 /// b.processNextNode();
1611 while ( !emptyQueue() ) processNextNode();
1614 /// \brief Executes the algorithm until the given target node is reached.
1616 /// Executes the algorithm until the given target node is reached.
1618 /// This method runs the %BFS algorithm from the root node(s)
1619 /// in order to compute the shortest path to \c dest.
1621 /// The algorithm computes
1622 /// - the shortest path to \c dest,
1623 /// - the distance of \c dest from the root(s).
1625 /// \pre init() must be called and at least one root node should be
1626 /// added with addSource() before using this function.
1628 /// \note <tt>b.start(t)</tt> is just a shortcut of the following code.
1630 /// bool reach = false;
1631 /// while ( !b.emptyQueue() && !reach ) {
1632 /// b.processNextNode(t, reach);
1635 void start(Node dest) {
1637 while ( !emptyQueue() && !reach ) processNextNode(dest, reach);
1640 /// \brief Executes the algorithm until a condition is met.
1642 /// Executes the algorithm until a condition is met.
1644 /// This method runs the %BFS algorithm from the root node(s) in
1645 /// order to compute the shortest path to a node \c v with
1646 /// <tt>nm[v]</tt> true, if such a node can be found.
1648 /// \param nm must be a bool (or convertible) node map. The
1649 /// algorithm will stop when it reaches a node \c v with
1650 /// <tt>nm[v]</tt> true.
1652 /// \return The reached node \c v with <tt>nm[v]</tt> true or
1653 /// \c INVALID if no such node was found.
1655 /// \pre init() must be called and at least one root node should be
1656 /// added with addSource() before using this function.
1658 /// \note <tt>b.start(nm)</tt> is just a shortcut of the following code.
1660 /// Node rnode = INVALID;
1661 /// while ( !b.emptyQueue() && rnode == INVALID ) {
1662 /// b.processNextNode(nm, rnode);
1666 template <typename NM>
1667 Node start(const NM &nm) {
1668 Node rnode = INVALID;
1669 while ( !emptyQueue() && rnode == INVALID ) {
1670 processNextNode(nm, rnode);
1675 /// \brief Runs the algorithm from the given node.
1677 /// This method runs the %BFS algorithm from node \c s
1678 /// in order to compute the shortest path to each node.
1680 /// The algorithm computes
1681 /// - the shortest path tree,
1682 /// - the distance of each node from the root.
1684 /// \note <tt>b.run(s)</tt> is just a shortcut of the following code.
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 result of the %BFS algorithm can be obtained using these
1730 /// Either \ref lemon::BfsVisit::run() "run()" or
1731 /// \ref lemon::BfsVisit::start() "start()" must be called before
1735 /// \brief Checks if a node is reachable from the root(s).
1737 /// Returns \c true if \c v is reachable from the root(s).
1738 /// \pre Either \ref run() or \ref start()
1739 /// must be called before using this function.
1740 bool reached(Node v) { return (*_reached)[v]; }
1746 } //END OF NAMESPACE LEMON