1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
3 * This file is a part of LEMON, a generic C++ optimization library.
5 * Copyright (C) 2003-2009
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
9 * Permission to use, modify and distribute this software is granted
10 * provided that this copyright notice appears in all copies. For
11 * precise terms see the accompanying LICENSE file.
13 * This software is provided "AS IS" with no warranty of any kind,
14 * express or implied, and with no claim as to its suitability for any
24 ///\brief BFS algorithm.
26 #include <lemon/list_graph.h>
27 #include <lemon/bits/path_dump.h>
28 #include <lemon/core.h>
29 #include <lemon/error.h>
30 #include <lemon/maps.h>
31 #include <lemon/path.h>
35 ///Default traits class of Bfs class.
37 ///Default traits class of Bfs class.
38 ///\tparam GR Digraph type.
40 struct BfsDefaultTraits
42 ///The type of the digraph the algorithm runs on.
45 ///\brief The type of the map that stores the predecessor
46 ///arcs of the shortest paths.
48 ///The type of the map that stores the predecessor
49 ///arcs of the shortest paths.
50 ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
51 typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
52 ///Instantiates a \c PredMap.
54 ///This function instantiates a \ref PredMap.
55 ///\param g is the digraph, to which we would like to define the
57 static PredMap *createPredMap(const Digraph &g)
59 return new PredMap(g);
62 ///The type of the map that indicates which nodes are processed.
64 ///The type of the map that indicates which nodes are processed.
65 ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
66 ///By default, it is a NullMap.
67 typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
68 ///Instantiates a \c ProcessedMap.
70 ///This function instantiates a \ref ProcessedMap.
71 ///\param g is the digraph, to which
72 ///we would like to define the \ref ProcessedMap
74 static ProcessedMap *createProcessedMap(const Digraph &g)
76 static ProcessedMap *createProcessedMap(const Digraph &)
79 return new ProcessedMap();
82 ///The type of the map that indicates which nodes are reached.
84 ///The type of the map that indicates which nodes are reached.
85 ///It must conform to the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
86 typedef typename Digraph::template NodeMap<bool> ReachedMap;
87 ///Instantiates a \c ReachedMap.
89 ///This function instantiates a \ref ReachedMap.
90 ///\param g is the digraph, to which
91 ///we would like to define the \ref ReachedMap.
92 static ReachedMap *createReachedMap(const Digraph &g)
94 return new ReachedMap(g);
97 ///The type of the map that stores the distances of the nodes.
99 ///The type of the map that stores the distances of the nodes.
100 ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
101 typedef typename Digraph::template NodeMap<int> DistMap;
102 ///Instantiates a \c DistMap.
104 ///This function instantiates a \ref DistMap.
105 ///\param g is the digraph, to which we would like to define the
107 static DistMap *createDistMap(const Digraph &g)
109 return new DistMap(g);
113 ///%BFS algorithm class.
116 ///This class provides an efficient implementation of the %BFS algorithm.
118 ///There is also a \ref bfs() "function-type interface" for the BFS
119 ///algorithm, which is convenient in the simplier cases and it can be
122 ///\tparam GR The type of the digraph the algorithm runs on.
123 ///The default type is \ref ListDigraph.
124 ///\tparam TR The traits class that defines various types used by the
125 ///algorithm. By default, it is \ref BfsDefaultTraits
126 ///"BfsDefaultTraits<GR>".
127 ///In most cases, this parameter should not be set directly,
128 ///consider to use the named template parameters instead.
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;
154 ///The \ref BfsDefaultTraits "traits class" of the algorithm.
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
232 ///\ref named-templ-param "Named parameter" for setting
234 ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
236 struct SetPredMap : public Bfs< Digraph, SetPredMapTraits<T> > {
237 typedef Bfs< Digraph, SetPredMapTraits<T> > Create;
241 struct SetDistMapTraits : public Traits {
243 static DistMap *createDistMap(const Digraph &)
245 LEMON_ASSERT(false, "DistMap is not initialized");
246 return 0; // ignore warnings
249 ///\brief \ref named-templ-param "Named parameter" for setting
252 ///\ref named-templ-param "Named parameter" for setting
254 ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
256 struct SetDistMap : public Bfs< Digraph, SetDistMapTraits<T> > {
257 typedef Bfs< Digraph, SetDistMapTraits<T> > Create;
261 struct SetReachedMapTraits : public Traits {
262 typedef T ReachedMap;
263 static ReachedMap *createReachedMap(const Digraph &)
265 LEMON_ASSERT(false, "ReachedMap is not initialized");
266 return 0; // ignore warnings
269 ///\brief \ref named-templ-param "Named parameter" for setting
270 ///\c ReachedMap type.
272 ///\ref named-templ-param "Named parameter" for setting
273 ///\c ReachedMap type.
274 ///It must conform to the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
276 struct SetReachedMap : public Bfs< Digraph, SetReachedMapTraits<T> > {
277 typedef Bfs< Digraph, SetReachedMapTraits<T> > Create;
281 struct SetProcessedMapTraits : public Traits {
282 typedef T ProcessedMap;
283 static ProcessedMap *createProcessedMap(const Digraph &)
285 LEMON_ASSERT(false, "ProcessedMap is not initialized");
286 return 0; // ignore warnings
289 ///\brief \ref named-templ-param "Named parameter" for setting
290 ///\c ProcessedMap type.
292 ///\ref named-templ-param "Named parameter" for setting
293 ///\c ProcessedMap type.
294 ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
296 struct SetProcessedMap : public Bfs< Digraph, SetProcessedMapTraits<T> > {
297 typedef Bfs< Digraph, SetProcessedMapTraits<T> > Create;
300 struct SetStandardProcessedMapTraits : public Traits {
301 typedef typename Digraph::template NodeMap<bool> ProcessedMap;
302 static ProcessedMap *createProcessedMap(const Digraph &g)
304 return new ProcessedMap(g);
305 return 0; // ignore warnings
308 ///\brief \ref named-templ-param "Named parameter" for setting
309 ///\c ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
311 ///\ref named-templ-param "Named parameter" for setting
312 ///\c ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
313 ///If you don't set it explicitly, it will be automatically allocated.
314 struct SetStandardProcessedMap :
315 public Bfs< Digraph, SetStandardProcessedMapTraits > {
316 typedef Bfs< Digraph, SetStandardProcessedMapTraits > Create;
326 ///\param g The digraph the algorithm runs on.
327 Bfs(const Digraph &g) :
329 _pred(NULL), local_pred(false),
330 _dist(NULL), local_dist(false),
331 _reached(NULL), local_reached(false),
332 _processed(NULL), local_processed(false)
338 if(local_pred) delete _pred;
339 if(local_dist) delete _dist;
340 if(local_reached) delete _reached;
341 if(local_processed) delete _processed;
344 ///Sets the map that stores the predecessor arcs.
346 ///Sets the map that stores the predecessor arcs.
347 ///If you don't use this function before calling \ref run(Node) "run()"
348 ///or \ref init(), an instance will be allocated automatically.
349 ///The destructor deallocates this automatically allocated map,
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(Node) "run()"
366 ///or \ref init(), an instance will be allocated automatically.
367 ///The destructor deallocates this automatically allocated map,
369 ///\return <tt> (*this) </tt>
370 Bfs &reachedMap(ReachedMap &m)
380 ///Sets the map that indicates which nodes are processed.
382 ///Sets the map that indicates which nodes are processed.
383 ///If you don't use this function before calling \ref run(Node) "run()"
384 ///or \ref init(), an instance will be allocated automatically.
385 ///The destructor deallocates this automatically allocated map,
387 ///\return <tt> (*this) </tt>
388 Bfs &processedMap(ProcessedMap &m)
390 if(local_processed) {
392 local_processed=false;
398 ///Sets the map that stores the distances of the nodes.
400 ///Sets the map that stores the distances of the nodes calculated by
402 ///If you don't use this function before calling \ref run(Node) "run()"
403 ///or \ref init(), an instance will be allocated automatically.
404 ///The destructor deallocates this automatically allocated map,
406 ///\return <tt> (*this) </tt>
407 Bfs &distMap(DistMap &m)
419 ///\name Execution Control
420 ///The simplest way to execute the BFS algorithm is to use one of the
421 ///member functions called \ref run(Node) "run()".\n
422 ///If you need better control on the execution, you have to call
423 ///\ref init() first, then you can add several source nodes with
424 ///\ref addSource(). Finally the actual path computation can be
425 ///performed with one of the \ref start() functions.
429 ///\brief Initializes the internal data structures.
431 ///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 ///Returns \c false if there are nodes to be processed.
567 ///Returns \c false if there are nodes to be processed
569 bool emptyQueue() const { return _queue_tail==_queue_head; }
571 ///Returns the number of the nodes to be processed.
573 ///Returns the number of the nodes to be processed
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 t.
609 ///The algorithm computes
610 ///- the shortest path to \c t,
611 ///- the distance of \c t 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);
626 while ( !emptyQueue() && !reach ) processNextNode(t, 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 source 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 node \c t
689 ///(it stops searching when \c t is processed).
691 ///\return \c true if \c t is reachable form \c s.
693 ///\note Apart from the return value, <tt>b.run(s,t)</tt> is just a
694 ///shortcut of the following code.
700 bool run(Node s,Node t) {
707 ///Runs the algorithm to visit all nodes in the digraph.
709 ///This method runs the %BFS algorithm in order to visit all nodes
712 ///\note <tt>b.run(s)</tt> is just a shortcut of the following code.
715 /// for (NodeIt n(gr); n != INVALID; ++n) {
716 /// if (!b.reached(n)) {
724 for (NodeIt n(*G); n != INVALID; ++n) {
734 ///\name Query Functions
735 ///The results of the BFS algorithm can be obtained using these
737 ///Either \ref run(Node) "run()" or \ref start() should be called
738 ///before using them.
742 ///The shortest path to the given node.
744 ///Returns the shortest path to the given node from the root(s).
746 ///\warning \c t should be reached from the root(s).
748 ///\pre Either \ref run(Node) "run()" or \ref init()
749 ///must be called before using this function.
750 Path path(Node t) const { return Path(*G, *_pred, t); }
752 ///The distance of the given node from the root(s).
754 ///Returns the distance of the given node from the root(s).
756 ///\warning If node \c v is not reached from the root(s), then
757 ///the return value of this function is undefined.
759 ///\pre Either \ref run(Node) "run()" or \ref init()
760 ///must be called before using this function.
761 int dist(Node v) const { return (*_dist)[v]; }
763 ///\brief Returns the 'previous arc' of the shortest path tree for
766 ///This function returns the 'previous arc' of the shortest path
767 ///tree for the node \c v, i.e. it returns the last arc of a
768 ///shortest path from a root to \c v. It is \c INVALID if \c v
769 ///is not reached from the root(s) or if \c v is a root.
771 ///The shortest path tree used here is equal to the shortest path
772 ///tree used in \ref predNode() and \ref predMap().
774 ///\pre Either \ref run(Node) "run()" or \ref init()
775 ///must be called before using this function.
776 Arc predArc(Node v) const { return (*_pred)[v];}
778 ///\brief Returns the 'previous node' of the shortest path tree for
781 ///This function returns the 'previous node' of the shortest path
782 ///tree for the node \c v, i.e. it returns the last but one node
783 ///of a shortest path from a root to \c v. It is \c INVALID
784 ///if \c v is not reached from the root(s) or if \c v is a root.
786 ///The shortest path tree used here is equal to the shortest path
787 ///tree used in \ref predArc() and \ref predMap().
789 ///\pre Either \ref run(Node) "run()" or \ref init()
790 ///must be called before using this function.
791 Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
792 G->source((*_pred)[v]); }
794 ///\brief Returns a const reference to the node map that stores the
795 /// distances of the nodes.
797 ///Returns a const reference to the node map that stores the distances
798 ///of the nodes calculated by the algorithm.
800 ///\pre Either \ref run(Node) "run()" or \ref init()
801 ///must be called before using this function.
802 const DistMap &distMap() const { return *_dist;}
804 ///\brief Returns a const reference to the node map that stores the
807 ///Returns a const reference to the node map that stores the predecessor
808 ///arcs, which form the shortest path tree (forest).
810 ///\pre Either \ref run(Node) "run()" or \ref init()
811 ///must be called before using this function.
812 const PredMap &predMap() const { return *_pred;}
814 ///Checks if the given node is reached from the root(s).
816 ///Returns \c true if \c v is reached from the root(s).
818 ///\pre Either \ref run(Node) "run()" or \ref init()
819 ///must be called before using this function.
820 bool reached(Node v) const { return (*_reached)[v]; }
825 ///Default traits class of bfs() function.
827 ///Default traits class of bfs() function.
828 ///\tparam GR Digraph type.
830 struct BfsWizardDefaultTraits
832 ///The type of the digraph the algorithm runs on.
835 ///\brief The type of the map that stores the predecessor
836 ///arcs of the shortest paths.
838 ///The type of the map that stores the predecessor
839 ///arcs of the shortest paths.
840 ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
841 typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
842 ///Instantiates a PredMap.
844 ///This function instantiates a PredMap.
845 ///\param g is the digraph, to which we would like to define the
847 static PredMap *createPredMap(const Digraph &g)
849 return new PredMap(g);
852 ///The type of the map that indicates which nodes are processed.
854 ///The type of the map that indicates which nodes are processed.
855 ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
856 ///By default, it is a NullMap.
857 typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
858 ///Instantiates a ProcessedMap.
860 ///This function instantiates a ProcessedMap.
861 ///\param g is the digraph, to which
862 ///we would like to define the ProcessedMap.
864 static ProcessedMap *createProcessedMap(const Digraph &g)
866 static ProcessedMap *createProcessedMap(const Digraph &)
869 return new ProcessedMap();
872 ///The type of the map that indicates which nodes are reached.
874 ///The type of the map that indicates which nodes are reached.
875 ///It must conform to the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
876 typedef typename Digraph::template NodeMap<bool> ReachedMap;
877 ///Instantiates a ReachedMap.
879 ///This function instantiates a ReachedMap.
880 ///\param g is the digraph, to which
881 ///we would like to define the ReachedMap.
882 static ReachedMap *createReachedMap(const Digraph &g)
884 return new ReachedMap(g);
887 ///The type of the map that stores the distances of the nodes.
889 ///The type of the map that stores the distances of the nodes.
890 ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
891 typedef typename Digraph::template NodeMap<int> DistMap;
892 ///Instantiates a DistMap.
894 ///This function instantiates a DistMap.
895 ///\param g is the digraph, to which we would like to define
897 static DistMap *createDistMap(const Digraph &g)
899 return new DistMap(g);
902 ///The type of the shortest paths.
904 ///The type of the shortest paths.
905 ///It must conform to the \ref concepts::Path "Path" concept.
906 typedef lemon::Path<Digraph> Path;
909 /// Default traits class used by BfsWizard
911 /// Default traits class used by BfsWizard.
912 /// \tparam GR The type of the digraph.
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, 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(Node) "run()" method, it uses the
961 /// functions 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 /// \tparam TR The traits class that defines various types used by the
969 class BfsWizard : public TR
973 typedef typename TR::Digraph Digraph;
975 typedef typename Digraph::Node Node;
976 typedef typename Digraph::NodeIt NodeIt;
977 typedef typename Digraph::Arc Arc;
978 typedef typename Digraph::OutArcIt OutArcIt;
980 typedef typename TR::PredMap PredMap;
981 typedef typename TR::DistMap DistMap;
982 typedef typename TR::ReachedMap ReachedMap;
983 typedef typename TR::ProcessedMap ProcessedMap;
984 typedef typename TR::Path Path;
989 BfsWizard() : TR() {}
991 /// Constructor that requires parameters.
993 /// Constructor that requires parameters.
994 /// These parameters will be the default values for the traits class.
995 /// \param g The digraph the algorithm runs on.
996 BfsWizard(const Digraph &g) :
1000 BfsWizard(const TR &b) : TR(b) {}
1004 ///Runs BFS algorithm from the given source node.
1006 ///This method runs BFS algorithm from node \c s
1007 ///in order to compute the shortest path to each node.
1010 Bfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
1012 alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1014 alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1016 alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
1017 if (Base::_processed)
1018 alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1025 ///Finds the shortest path between \c s and \c t.
1027 ///This method runs BFS algorithm from node \c s
1028 ///in order to compute the shortest path to node \c t
1029 ///(it stops searching when \c t is processed).
1031 ///\return \c true if \c t is reachable form \c s.
1032 bool run(Node s, Node t)
1034 Bfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
1036 alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1038 alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1040 alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
1041 if (Base::_processed)
1042 alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1045 *reinterpret_cast<Path*>(Base::_path) = alg.path(t);
1047 *Base::_di = alg.dist(t);
1048 return alg.reached(t);
1051 ///Runs BFS algorithm to visit all nodes in the digraph.
1053 ///This method runs BFS algorithm in order to visit all nodes
1061 struct SetPredMapBase : public Base {
1063 static PredMap *createPredMap(const Digraph &) { return 0; };
1064 SetPredMapBase(const TR &b) : TR(b) {}
1067 ///\brief \ref named-templ-param "Named parameter" for setting
1068 ///the predecessor map.
1070 ///\ref named-templ-param "Named parameter" function for setting
1071 ///the map that stores the predecessor arcs of the nodes.
1073 BfsWizard<SetPredMapBase<T> > predMap(const T &t)
1075 Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1076 return BfsWizard<SetPredMapBase<T> >(*this);
1080 struct SetReachedMapBase : public Base {
1081 typedef T ReachedMap;
1082 static ReachedMap *createReachedMap(const Digraph &) { return 0; };
1083 SetReachedMapBase(const TR &b) : TR(b) {}
1086 ///\brief \ref named-templ-param "Named parameter" for setting
1089 ///\ref named-templ-param "Named parameter" function for setting
1090 ///the map that indicates which nodes are reached.
1092 BfsWizard<SetReachedMapBase<T> > reachedMap(const T &t)
1094 Base::_reached=reinterpret_cast<void*>(const_cast<T*>(&t));
1095 return BfsWizard<SetReachedMapBase<T> >(*this);
1099 struct SetDistMapBase : public Base {
1101 static DistMap *createDistMap(const Digraph &) { return 0; };
1102 SetDistMapBase(const TR &b) : TR(b) {}
1105 ///\brief \ref named-templ-param "Named parameter" for setting
1106 ///the distance map.
1108 ///\ref named-templ-param "Named parameter" function for setting
1109 ///the map that stores the distances of the nodes calculated
1110 ///by the algorithm.
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) {}
1125 ///\brief \ref named-func-param "Named parameter" for setting
1126 ///the processed map.
1128 ///\ref named-templ-param "Named parameter" function for setting
1129 ///the map that indicates which nodes are processed.
1131 BfsWizard<SetProcessedMapBase<T> > processedMap(const T &t)
1133 Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1134 return BfsWizard<SetProcessedMapBase<T> >(*this);
1138 struct SetPathBase : public Base {
1140 SetPathBase(const TR &b) : TR(b) {}
1142 ///\brief \ref named-func-param "Named parameter"
1143 ///for getting the shortest path to the target node.
1145 ///\ref named-func-param "Named parameter"
1146 ///for getting the shortest path to the target node.
1148 BfsWizard<SetPathBase<T> > path(const T &t)
1150 Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t));
1151 return BfsWizard<SetPathBase<T> >(*this);
1154 ///\brief \ref named-func-param "Named parameter"
1155 ///for getting the distance of the target node.
1157 ///\ref named-func-param "Named parameter"
1158 ///for getting the distance of the target node.
1159 BfsWizard dist(const int &d)
1161 Base::_di=const_cast<int*>(&d);
1167 ///Function-type interface for BFS algorithm.
1170 ///Function-type interface for BFS algorithm.
1172 ///This function also has several \ref named-func-param "named parameters",
1173 ///they are declared as the members of class \ref BfsWizard.
1174 ///The following examples show how to use these parameters.
1176 /// // Compute shortest path from node s to each node
1177 /// bfs(g).predMap(preds).distMap(dists).run(s);
1179 /// // Compute shortest path from s to t
1180 /// bool reached = bfs(g).path(p).dist(d).run(s,t);
1182 ///\warning Don't forget to put the \ref BfsWizard::run(Node) "run()"
1183 ///to the end of the parameter list.
1187 BfsWizard<BfsWizardBase<GR> >
1188 bfs(const GR &digraph)
1190 return BfsWizard<BfsWizardBase<GR> >(digraph);
1194 /// \brief Visitor class for BFS.
1196 /// This class defines the interface of the BfsVisit events, and
1197 /// it could be the base of a real visitor class.
1198 template <typename GR>
1201 typedef typename Digraph::Arc Arc;
1202 typedef typename Digraph::Node Node;
1203 /// \brief Called for the source node(s) of the BFS.
1205 /// This function is called for the source node(s) of the BFS.
1206 void start(const Node& node) {}
1207 /// \brief Called when a node is reached first time.
1209 /// This function is called when a node is reached first time.
1210 void reach(const Node& node) {}
1211 /// \brief Called when a node is processed.
1213 /// This function is called when a node is processed.
1214 void process(const Node& node) {}
1215 /// \brief Called when an arc reaches a new node.
1217 /// This function is called when the BFS finds an arc whose target node
1218 /// is not reached yet.
1219 void discover(const Arc& arc) {}
1220 /// \brief Called when an arc is examined but its target node is
1221 /// already discovered.
1223 /// This function is called when an arc is examined but its target node is
1224 /// already discovered.
1225 void examine(const Arc& arc) {}
1228 template <typename GR>
1231 typedef typename Digraph::Arc Arc;
1232 typedef typename Digraph::Node Node;
1233 void start(const Node&) {}
1234 void reach(const Node&) {}
1235 void process(const Node&) {}
1236 void discover(const Arc&) {}
1237 void examine(const Arc&) {}
1239 template <typename _Visitor>
1240 struct Constraints {
1241 void constraints() {
1244 visitor.start(node);
1245 visitor.reach(node);
1246 visitor.process(node);
1247 visitor.discover(arc);
1248 visitor.examine(arc);
1255 /// \brief Default traits class of BfsVisit class.
1257 /// Default traits class of BfsVisit class.
1258 /// \tparam GR The type of the digraph the algorithm runs on.
1260 struct BfsVisitDefaultTraits {
1262 /// \brief The type of the digraph the algorithm runs on.
1265 /// \brief The type of the map that indicates which nodes are reached.
1267 /// The type of the map that indicates which nodes are reached.
1268 /// It must conform to the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
1269 typedef typename Digraph::template NodeMap<bool> ReachedMap;
1271 /// \brief Instantiates a ReachedMap.
1273 /// This function instantiates a ReachedMap.
1274 /// \param digraph is the digraph, to which
1275 /// we would like to define the ReachedMap.
1276 static ReachedMap *createReachedMap(const Digraph &digraph) {
1277 return new ReachedMap(digraph);
1284 /// \brief BFS algorithm class with visitor interface.
1286 /// This class provides an efficient implementation of the BFS algorithm
1287 /// with visitor interface.
1289 /// The BfsVisit class provides an alternative interface to the Bfs
1290 /// class. It works with callback mechanism, the BfsVisit object calls
1291 /// the member functions of the \c Visitor class on every BFS event.
1293 /// This interface of the BFS algorithm should be used in special cases
1294 /// when extra actions have to be performed in connection with certain
1295 /// events of the BFS algorithm. Otherwise consider to use Bfs or bfs()
1298 /// \tparam GR The type of the digraph the algorithm runs on.
1299 /// The default type is \ref ListDigraph.
1300 /// The value of GR is not used directly by \ref BfsVisit,
1301 /// it is only passed to \ref BfsVisitDefaultTraits.
1302 /// \tparam VS The Visitor type that is used by the algorithm.
1303 /// \ref BfsVisitor "BfsVisitor<GR>" is an empty visitor, which
1304 /// does not observe the BFS events. If you want to observe the BFS
1305 /// events, you should implement your own visitor class.
1306 /// \tparam TR The traits class that defines various types used by the
1307 /// algorithm. By default, it is \ref BfsVisitDefaultTraits
1308 /// "BfsVisitDefaultTraits<GR>".
1309 /// In most cases, this parameter should not be set directly,
1310 /// consider to use the named template parameters instead.
1312 template <typename GR, typename VS, typename TR>
1314 template <typename GR = ListDigraph,
1315 typename VS = BfsVisitor<GR>,
1316 typename TR = BfsVisitDefaultTraits<GR> >
1321 ///The traits class.
1324 ///The type of the digraph the algorithm runs on.
1325 typedef typename Traits::Digraph Digraph;
1327 ///The visitor type used by the algorithm.
1330 ///The type of the map that indicates which nodes are reached.
1331 typedef typename Traits::ReachedMap ReachedMap;
1335 typedef typename Digraph::Node Node;
1336 typedef typename Digraph::NodeIt NodeIt;
1337 typedef typename Digraph::Arc Arc;
1338 typedef typename Digraph::OutArcIt OutArcIt;
1340 //Pointer to the underlying digraph.
1341 const Digraph *_digraph;
1342 //Pointer to the visitor object.
1344 //Pointer to the map of reached status of the nodes.
1345 ReachedMap *_reached;
1346 //Indicates if _reached is locally allocated (true) or not.
1349 std::vector<typename Digraph::Node> _list;
1350 int _list_front, _list_back;
1352 //Creates the maps if necessary.
1353 void create_maps() {
1355 local_reached = true;
1356 _reached = Traits::createReachedMap(*_digraph);
1366 typedef BfsVisit Create;
1368 /// \name Named Template Parameters
1372 struct SetReachedMapTraits : public Traits {
1373 typedef T ReachedMap;
1374 static ReachedMap *createReachedMap(const Digraph &digraph) {
1375 LEMON_ASSERT(false, "ReachedMap is not initialized");
1376 return 0; // ignore warnings
1379 /// \brief \ref named-templ-param "Named parameter" for setting
1380 /// ReachedMap type.
1382 /// \ref named-templ-param "Named parameter" for setting ReachedMap type.
1384 struct SetReachedMap : public BfsVisit< Digraph, Visitor,
1385 SetReachedMapTraits<T> > {
1386 typedef BfsVisit< Digraph, Visitor, SetReachedMapTraits<T> > Create;
1392 /// \brief Constructor.
1396 /// \param digraph The digraph the algorithm runs on.
1397 /// \param visitor The visitor object of the algorithm.
1398 BfsVisit(const Digraph& digraph, Visitor& visitor)
1399 : _digraph(&digraph), _visitor(&visitor),
1400 _reached(0), local_reached(false) {}
1402 /// \brief Destructor.
1404 if(local_reached) delete _reached;
1407 /// \brief Sets the map that indicates which nodes are reached.
1409 /// Sets the map that indicates which nodes are reached.
1410 /// If you don't use this function before calling \ref run(Node) "run()"
1411 /// or \ref init(), an instance will be allocated automatically.
1412 /// The destructor deallocates this automatically allocated map,
1414 /// \return <tt> (*this) </tt>
1415 BfsVisit &reachedMap(ReachedMap &m) {
1418 local_reached = false;
1426 /// \name Execution Control
1427 /// The simplest way to execute the BFS algorithm is to use one of the
1428 /// member functions called \ref run(Node) "run()".\n
1429 /// If you need better control on the execution, you have to call
1430 /// \ref init() first, then you can add several source nodes with
1431 /// \ref addSource(). Finally the actual path computation can be
1432 /// performed with one of the \ref start() functions.
1436 /// \brief Initializes the internal data structures.
1438 /// Initializes the internal data structures.
1441 _list.resize(countNodes(*_digraph));
1442 _list_front = _list_back = -1;
1443 for (NodeIt u(*_digraph) ; u != INVALID ; ++u) {
1444 _reached->set(u, false);
1448 /// \brief Adds a new source node.
1450 /// Adds a new source node to the set of nodes to be processed.
1451 void addSource(Node s) {
1452 if(!(*_reached)[s]) {
1453 _reached->set(s,true);
1456 _list[++_list_back] = s;
1460 /// \brief Processes the next node.
1462 /// Processes the next node.
1464 /// \return The processed node.
1466 /// \pre The queue must not be empty.
1467 Node processNextNode() {
1468 Node n = _list[++_list_front];
1469 _visitor->process(n);
1471 for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1472 Node m = _digraph->target(e);
1473 if (!(*_reached)[m]) {
1474 _visitor->discover(e);
1476 _reached->set(m, true);
1477 _list[++_list_back] = m;
1479 _visitor->examine(e);
1485 /// \brief Processes the next node.
1487 /// Processes the next node and checks if the given target node
1488 /// is reached. If the target node is reachable from the processed
1489 /// node, then the \c reach parameter will be set to \c true.
1491 /// \param target The target node.
1492 /// \retval reach Indicates if the target node is reached.
1493 /// It should be initially \c false.
1495 /// \return The processed node.
1497 /// \pre The queue must not be empty.
1498 Node processNextNode(Node target, bool& reach) {
1499 Node n = _list[++_list_front];
1500 _visitor->process(n);
1502 for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1503 Node m = _digraph->target(e);
1504 if (!(*_reached)[m]) {
1505 _visitor->discover(e);
1507 _reached->set(m, true);
1508 _list[++_list_back] = m;
1509 reach = reach || (target == m);
1511 _visitor->examine(e);
1517 /// \brief Processes the next node.
1519 /// Processes the next node and checks if at least one of reached
1520 /// nodes has \c true value in the \c nm node map. If one node
1521 /// with \c true value is reachable from the processed node, then the
1522 /// \c rnode parameter will be set to the first of such nodes.
1524 /// \param nm A \c bool (or convertible) node map that indicates the
1525 /// possible targets.
1526 /// \retval rnode The reached target node.
1527 /// It should be initially \c INVALID.
1529 /// \return The processed node.
1531 /// \pre The queue must not be empty.
1532 template <typename NM>
1533 Node processNextNode(const NM& nm, Node& rnode) {
1534 Node n = _list[++_list_front];
1535 _visitor->process(n);
1537 for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1538 Node m = _digraph->target(e);
1539 if (!(*_reached)[m]) {
1540 _visitor->discover(e);
1542 _reached->set(m, true);
1543 _list[++_list_back] = m;
1544 if (nm[m] && rnode == INVALID) rnode = m;
1546 _visitor->examine(e);
1552 /// \brief The next node to be processed.
1554 /// Returns the next node to be processed or \c INVALID if the queue
1556 Node nextNode() const {
1557 return _list_front != _list_back ? _list[_list_front + 1] : INVALID;
1560 /// \brief Returns \c false if there are nodes
1561 /// to be processed.
1563 /// Returns \c false if there are nodes
1564 /// to be processed in the queue.
1565 bool emptyQueue() const { return _list_front == _list_back; }
1567 /// \brief Returns the number of the nodes to be processed.
1569 /// Returns the number of the nodes to be processed in the queue.
1570 int queueSize() const { return _list_back - _list_front; }
1572 /// \brief Executes the algorithm.
1574 /// Executes the algorithm.
1576 /// This method runs the %BFS algorithm from the root node(s)
1577 /// in order to compute the shortest path to each node.
1579 /// The algorithm computes
1580 /// - the shortest path tree (forest),
1581 /// - the distance of each node from the root(s).
1583 /// \pre init() must be called and at least one root node should be added
1584 /// with addSource() before using this function.
1586 /// \note <tt>b.start()</tt> is just a shortcut of the following code.
1588 /// while ( !b.emptyQueue() ) {
1589 /// b.processNextNode();
1593 while ( !emptyQueue() ) processNextNode();
1596 /// \brief Executes the algorithm until the given target node is reached.
1598 /// Executes the algorithm until the given target node is reached.
1600 /// This method runs the %BFS algorithm from the root node(s)
1601 /// in order to compute the shortest path to \c t.
1603 /// The algorithm computes
1604 /// - the shortest path to \c t,
1605 /// - the distance of \c t from the root(s).
1607 /// \pre init() must be called and at least one root node should be
1608 /// added with addSource() before using this function.
1610 /// \note <tt>b.start(t)</tt> is just a shortcut of the following code.
1612 /// bool reach = false;
1613 /// while ( !b.emptyQueue() && !reach ) {
1614 /// b.processNextNode(t, reach);
1617 void start(Node t) {
1619 while ( !emptyQueue() && !reach ) processNextNode(t, reach);
1622 /// \brief Executes the algorithm until a condition is met.
1624 /// Executes the algorithm until a condition is met.
1626 /// This method runs the %BFS algorithm from the root node(s) in
1627 /// order to compute the shortest path to a node \c v with
1628 /// <tt>nm[v]</tt> true, if such a node can be found.
1630 /// \param nm must be a bool (or convertible) node map. The
1631 /// algorithm will stop when it reaches a node \c v with
1632 /// <tt>nm[v]</tt> true.
1634 /// \return The reached node \c v with <tt>nm[v]</tt> true or
1635 /// \c INVALID if no such node was found.
1637 /// \pre init() must be called and at least one root node should be
1638 /// added with addSource() before using this function.
1640 /// \note <tt>b.start(nm)</tt> is just a shortcut of the following code.
1642 /// Node rnode = INVALID;
1643 /// while ( !b.emptyQueue() && rnode == INVALID ) {
1644 /// b.processNextNode(nm, rnode);
1648 template <typename NM>
1649 Node start(const NM &nm) {
1650 Node rnode = INVALID;
1651 while ( !emptyQueue() && rnode == INVALID ) {
1652 processNextNode(nm, rnode);
1657 /// \brief Runs the algorithm from the given source node.
1659 /// This method runs the %BFS algorithm from node \c s
1660 /// in order to compute the shortest path to each node.
1662 /// The algorithm computes
1663 /// - the shortest path tree,
1664 /// - the distance of each node from the root.
1666 /// \note <tt>b.run(s)</tt> is just a shortcut of the following code.
1678 /// \brief Finds the shortest path between \c s and \c t.
1680 /// This method runs the %BFS algorithm from node \c s
1681 /// in order to compute the shortest path to node \c t
1682 /// (it stops searching when \c t is processed).
1684 /// \return \c true if \c t is reachable form \c s.
1686 /// \note Apart from the return value, <tt>b.run(s,t)</tt> is just a
1687 /// shortcut of the following code.
1693 bool run(Node s,Node t) {
1700 /// \brief Runs the algorithm to visit all nodes in the digraph.
1702 /// This method runs the %BFS algorithm in order to visit all nodes
1705 /// \note <tt>b.run(s)</tt> is just a shortcut of the following code.
1708 /// for (NodeIt n(gr); n != INVALID; ++n) {
1709 /// if (!b.reached(n)) {
1717 for (NodeIt it(*_digraph); it != INVALID; ++it) {
1727 /// \name Query Functions
1728 /// The results of the BFS algorithm can be obtained using these
1730 /// Either \ref run(Node) "run()" or \ref start() should be called
1731 /// before using them.
1735 /// \brief Checks if the given node is reached from the root(s).
1737 /// Returns \c true if \c v is reached from the root(s).
1739 /// \pre Either \ref run(Node) "run()" or \ref init()
1740 /// must be called before using this function.
1741 bool reached(Node v) const { return (*_reached)[v]; }
1747 } //END OF NAMESPACE LEMON