CMake improvements.
- documentation generation with Doxygen
- installation support
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 Dfs algorithm.
26 #include <lemon/list_graph.h>
27 #include <lemon/graph_utils.h>
28 #include <lemon/bits/path_dump.h>
29 #include <lemon/bits/invalid.h>
30 #include <lemon/error.h>
31 #include <lemon/maps.h>
33 #include <lemon/concept_check.h>
38 ///Default traits class of Dfs class.
40 ///Default traits class of Dfs class.
41 ///\tparam GR Digraph type.
43 struct DfsDefaultTraits
45 ///The digraph type the algorithm runs on.
47 ///\brief The type of the map that stores the last
48 ///arcs of the %DFS paths.
50 ///The type of the map that stores the last
51 ///arcs of the %DFS paths.
52 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
54 typedef typename Digraph::template NodeMap<typename GR::Arc> PredMap;
55 ///Instantiates a PredMap.
57 ///This function instantiates a \ref PredMap.
58 ///\param G is the digraph, to which we would like to define the PredMap.
59 ///\todo The digraph alone may be insufficient to initialize
60 static PredMap *createPredMap(const GR &G)
62 return new PredMap(G);
65 ///The type of the map that indicates which nodes are processed.
67 ///The type of the map that indicates which nodes are processed.
68 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
69 ///\todo named parameter to set this type, function to read and write.
70 typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
71 ///Instantiates a ProcessedMap.
73 ///This function instantiates a \ref ProcessedMap.
74 ///\param g is the digraph, to which
75 ///we would like to define the \ref ProcessedMap
77 static ProcessedMap *createProcessedMap(const GR &g)
79 static ProcessedMap *createProcessedMap(const GR &)
82 return new ProcessedMap();
84 ///The type of the map that indicates which nodes are reached.
86 ///The type of the map that indicates which nodes are reached.
87 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
88 ///\todo named parameter to set this type, function to read and write.
89 typedef typename Digraph::template NodeMap<bool> ReachedMap;
90 ///Instantiates a ReachedMap.
92 ///This function instantiates a \ref ReachedMap.
93 ///\param G is the digraph, to which
94 ///we would like to define the \ref ReachedMap.
95 static ReachedMap *createReachedMap(const GR &G)
97 return new ReachedMap(G);
99 ///The type of the map that stores the dists of the nodes.
101 ///The type of the map that stores the dists of the nodes.
102 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
104 typedef typename Digraph::template NodeMap<int> DistMap;
105 ///Instantiates a DistMap.
107 ///This function instantiates a \ref DistMap.
108 ///\param G is the digraph, to which we would like to define
110 static DistMap *createDistMap(const GR &G)
112 return new DistMap(G);
116 ///%DFS algorithm class.
119 ///This class provides an efficient implementation of the %DFS algorithm.
121 ///\tparam GR The digraph type the algorithm runs on. The default value is
122 ///\ref ListDigraph. The value of GR is not used directly by Dfs, it
123 ///is only passed to \ref DfsDefaultTraits.
124 ///\tparam TR Traits class to set various data types used by the algorithm.
125 ///The default traits class is
126 ///\ref DfsDefaultTraits "DfsDefaultTraits<GR>".
127 ///See \ref DfsDefaultTraits for the documentation of
128 ///a Dfs traits class.
130 template <typename GR,
133 template <typename GR=ListDigraph,
134 typename TR=DfsDefaultTraits<GR> >
139 * \brief \ref Exception for uninitialized parameters.
141 * This error represents problems in the initialization
142 * of the parameters of the algorithms.
144 class UninitializedParameter : public lemon::UninitializedParameter {
146 virtual const char* what() const throw() {
147 return "lemon::Dfs::UninitializedParameter";
152 ///The type of the underlying digraph.
153 typedef typename TR::Digraph Digraph;
155 typedef typename Digraph::Node Node;
157 typedef typename Digraph::NodeIt NodeIt;
159 typedef typename Digraph::Arc Arc;
161 typedef typename Digraph::OutArcIt OutArcIt;
163 ///\brief The type of the map that stores the last
164 ///arcs of the %DFS paths.
165 typedef typename TR::PredMap PredMap;
166 ///The type of the map indicating which nodes are reached.
167 typedef typename TR::ReachedMap ReachedMap;
168 ///The type of the map indicating which nodes are processed.
169 typedef typename TR::ProcessedMap ProcessedMap;
170 ///The type of the map that stores the dists of the nodes.
171 typedef typename TR::DistMap DistMap;
173 /// Pointer to the underlying digraph.
175 ///Pointer to the map of predecessors arcs.
177 ///Indicates if \ref _pred is locally allocated (\c true) or not.
179 ///Pointer to the map of distances.
181 ///Indicates if \ref _dist is locally allocated (\c true) or not.
183 ///Pointer to the map of reached status of the nodes.
184 ReachedMap *_reached;
185 ///Indicates if \ref _reached is locally allocated (\c true) or not.
187 ///Pointer to the map of processed status of the nodes.
188 ProcessedMap *_processed;
189 ///Indicates if \ref _processed is locally allocated (\c true) or not.
190 bool local_processed;
192 std::vector<typename Digraph::OutArcIt> _stack;
195 ///Creates the maps if necessary.
197 ///\todo Better memory allocation (instead of new).
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 DefPredMapTraits : public Traits {
233 static PredMap *createPredMap(const Digraph &G)
235 throw UninitializedParameter();
238 ///\brief \ref named-templ-param "Named parameter" for setting
241 ///\ref named-templ-param "Named parameter" for setting PredMap type
244 struct DefPredMap : public Dfs<Digraph, DefPredMapTraits<T> > {
245 typedef Dfs<Digraph, DefPredMapTraits<T> > Create;
250 struct DefDistMapTraits : public Traits {
252 static DistMap *createDistMap(const Digraph &)
254 throw UninitializedParameter();
257 ///\brief \ref named-templ-param "Named parameter" for setting
260 ///\ref named-templ-param "Named parameter" for setting DistMap
264 typedef Dfs<Digraph, DefDistMapTraits<T> > Create;
268 struct DefReachedMapTraits : public Traits {
269 typedef T ReachedMap;
270 static ReachedMap *createReachedMap(const Digraph &)
272 throw UninitializedParameter();
275 ///\brief \ref named-templ-param "Named parameter" for setting
278 ///\ref named-templ-param "Named parameter" for setting ReachedMap type
281 struct DefReachedMap : public Dfs< Digraph, DefReachedMapTraits<T> > {
282 typedef Dfs< Digraph, DefReachedMapTraits<T> > Create;
286 struct DefProcessedMapTraits : public Traits {
287 typedef T ProcessedMap;
288 static ProcessedMap *createProcessedMap(const Digraph &)
290 throw UninitializedParameter();
293 ///\brief \ref named-templ-param "Named parameter" for setting
296 ///\ref named-templ-param "Named parameter" for setting ProcessedMap type
299 struct DefProcessedMap : public Dfs< Digraph, DefProcessedMapTraits<T> > {
300 typedef Dfs< Digraph, DefProcessedMapTraits<T> > Create;
303 struct DefDigraphProcessedMapTraits : public Traits {
304 typedef typename Digraph::template NodeMap<bool> ProcessedMap;
305 static ProcessedMap *createProcessedMap(const Digraph &G)
307 return new ProcessedMap(G);
310 ///\brief \ref named-templ-param "Named parameter"
311 ///for setting the ProcessedMap type to be Digraph::NodeMap<bool>.
313 ///\ref named-templ-param "Named parameter"
314 ///for setting the ProcessedMap type to be Digraph::NodeMap<bool>.
315 ///If you don't set it explicitely, it will be automatically allocated.
317 class DefProcessedMapToBeDefaultMap :
318 public Dfs< Digraph, DefDigraphProcessedMapTraits> {
319 typedef Dfs< Digraph, DefDigraphProcessedMapTraits> Create;
328 ///\param _G the digraph the algorithm will run on.
330 Dfs(const Digraph& _G) :
332 _pred(NULL), local_pred(false),
333 _dist(NULL), local_dist(false),
334 _reached(NULL), local_reached(false),
335 _processed(NULL), local_processed(false)
341 if(local_pred) delete _pred;
342 if(local_dist) delete _dist;
343 if(local_reached) delete _reached;
344 if(local_processed) delete _processed;
347 ///Sets the map storing the predecessor arcs.
349 ///Sets the map storing the predecessor arcs.
350 ///If you don't use this function before calling \ref run(),
351 ///it will allocate one. The destuctor deallocates this
352 ///automatically allocated map, of course.
353 ///\return <tt> (*this) </tt>
354 Dfs &predMap(PredMap &m)
364 ///Sets the map storing the distances calculated by the algorithm.
366 ///Sets the map storing the distances calculated by the algorithm.
367 ///If you don't use this function before calling \ref run(),
368 ///it will allocate one. The destuctor deallocates this
369 ///automatically allocated map, of course.
370 ///\return <tt> (*this) </tt>
371 Dfs &distMap(DistMap &m)
381 ///Sets the map indicating if a node is reached.
383 ///Sets the map indicating if a node is reached.
384 ///If you don't use this function before calling \ref run(),
385 ///it will allocate one. The destuctor deallocates this
386 ///automatically allocated map, of course.
387 ///\return <tt> (*this) </tt>
388 Dfs &reachedMap(ReachedMap &m)
398 ///Sets the map indicating if a node is processed.
400 ///Sets the map indicating if a node is processed.
401 ///If you don't use this function before calling \ref run(),
402 ///it will allocate one. The destuctor deallocates this
403 ///automatically allocated map, of course.
404 ///\return <tt> (*this) </tt>
405 Dfs &processedMap(ProcessedMap &m)
407 if(local_processed) {
409 local_processed=false;
416 ///\name Execution control
417 ///The simplest way to execute the algorithm is to use
418 ///one of the member functions called \c run(...).
420 ///If you need more control on the execution,
421 ///first you must call \ref init(), then you can add a source node
422 ///with \ref addSource().
423 ///Finally \ref start() will perform the actual path
428 ///Initializes the internal data structures.
430 ///Initializes the internal data structures.
435 _stack.resize(countNodes(*G));
437 for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
438 _pred->set(u,INVALID);
439 // _predNode->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 ///\warning dists are wrong (or at least strange)
450 ///in case of multiple sources.
451 void addSource(Node s)
455 _reached->set(s,true);
456 _pred->set(s,INVALID);
459 _stack[++_stack_head]=e;
460 _dist->set(s,_stack_head);
463 _processed->set(s,true);
469 ///Processes the next arc.
471 ///Processes the next arc.
473 ///\return The processed arc.
475 ///\pre The stack must not be empty!
479 Arc e=_stack[_stack_head];
480 if(!(*_reached)[m=G->target(e)]) {
482 _reached->set(m,true);
484 _stack[_stack_head] = OutArcIt(*G, m);
485 _dist->set(m,_stack_head);
489 ++_stack[_stack_head];
491 while(_stack_head>=0 && _stack[_stack_head]==INVALID) {
492 _processed->set(m,true);
495 m=G->source(_stack[_stack_head]);
496 ++_stack[_stack_head];
501 ///Next arc to be processed.
503 ///Next arc to be processed.
505 ///\return The next arc to be processed or INVALID if the stack is
509 return _stack_head>=0?_stack[_stack_head]:INVALID;
512 ///\brief Returns \c false if there are nodes
513 ///to be processed in the queue
515 ///Returns \c false if there are nodes
516 ///to be processed in the queue
517 bool emptyQueue() { return _stack_head<0; }
518 ///Returns the number of the nodes to be processed.
520 ///Returns the number of the nodes to be processed in the queue.
521 int queueSize() { return _stack_head+1; }
523 ///Executes the algorithm.
525 ///Executes the algorithm.
527 ///\pre init() must be called and at least one node should be added
528 ///with addSource() before using this function.
530 ///This method runs the %DFS algorithm from the root node(s)
533 ///%DFS path to each node. The algorithm computes
535 ///- The distance of each node from the root(s) in the %DFS tree.
539 while ( !emptyQueue() ) processNextArc();
542 ///Executes the algorithm until \c dest is reached.
544 ///Executes the algorithm until \c dest is reached.
546 ///\pre init() must be called and at least one node should be added
547 ///with addSource() before using this function.
549 ///This method runs the %DFS algorithm from the root node(s)
552 ///%DFS path to \c dest. The algorithm computes
553 ///- The %DFS path to \c dest.
554 ///- The distance of \c dest from the root(s) in the %DFS tree.
556 void start(Node dest)
558 while ( !emptyQueue() && G->target(_stack[_stack_head])!=dest )
562 ///Executes the algorithm until a condition is met.
564 ///Executes the algorithm until a condition is met.
566 ///\pre init() must be called and at least one node should be added
567 ///with addSource() before using this function.
569 ///\param em must be a bool (or convertible) arc map. The algorithm
570 ///will stop when it reaches an arc \c e with <tt>em[e]</tt> true.
572 ///\return The reached arc \c e with <tt>em[e]</tt> true or
573 ///\c INVALID if no such arc was found.
575 ///\warning Contrary to \ref Bfs and \ref Dijkstra, \c em is an arc map,
578 Arc start(const EM &em)
580 while ( !emptyQueue() && !em[_stack[_stack_head]] )
582 return emptyQueue() ? INVALID : _stack[_stack_head];
585 ///Runs %DFS algorithm to visit all nodes in the digraph.
587 ///This method runs the %DFS algorithm in order to
589 ///%DFS path to each node. The algorithm computes
591 ///- The distance of each node from the root in the %DFS tree.
593 ///\note d.run() is just a shortcut of the following code.
596 /// for (NodeIt it(digraph); it != INVALID; ++it) {
597 /// if (!d.reached(it)) {
605 for (NodeIt it(*G); it != INVALID; ++it) {
613 ///Runs %DFS algorithm from node \c s.
615 ///This method runs the %DFS algorithm from a root node \c s
618 ///%DFS path to each node. The algorithm computes
620 ///- The distance of each node from the root in the %DFS tree.
622 ///\note d.run(s) is just a shortcut of the following code.
634 ///Finds the %DFS path between \c s and \c t.
636 ///Finds the %DFS path between \c s and \c t.
638 ///\return The length of the %DFS s---t path if there exists one,
640 ///\note Apart from the return value, d.run(s,t) is
641 ///just a shortcut of the following code.
647 int run(Node s,Node t) {
651 return reached(t)?_stack_head+1:0;
656 ///\name Query Functions
657 ///The result of the %DFS algorithm can be obtained using these
659 ///Before the use of these functions,
660 ///either run() or start() must be called.
664 typedef PredMapPath<Digraph, PredMap> Path;
666 ///Gives back the shortest path.
668 ///Gives back the shortest path.
669 ///\pre The \c t should be reachable from the source.
672 return Path(*G, *_pred, t);
675 ///The distance of a node from the root(s).
677 ///Returns the distance of a node from the root(s).
678 ///\pre \ref run() must be called before using this function.
679 ///\warning If node \c v is unreachable from the root(s) then the return
680 ///value of this funcion is undefined.
681 int dist(Node v) const { return (*_dist)[v]; }
683 ///Returns the 'previous arc' of the %DFS tree.
685 ///For a node \c v it returns the 'previous arc'
687 ///i.e. it returns the last arc of a %DFS path from the root(s) to \c
688 ///v. It is \ref INVALID
689 ///if \c v is unreachable from the root(s) or \c v is a root. The
690 ///%DFS tree used here is equal to the %DFS tree used in
692 ///\pre Either \ref run() or \ref start() must be called before using
694 Arc predArc(Node v) const { return (*_pred)[v];}
696 ///Returns the 'previous node' of the %DFS tree.
698 ///For a node \c v it returns the 'previous node'
700 ///i.e. it returns the last but one node from a %DFS path from the
702 ///It is INVALID if \c v is unreachable from the root(s) or
703 ///if \c v itself a root.
704 ///The %DFS tree used here is equal to the %DFS
705 ///tree used in \ref predArc().
706 ///\pre Either \ref run() or \ref start() must be called before
707 ///using this function.
708 Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
709 G->source((*_pred)[v]); }
711 ///Returns a reference to the NodeMap of distances.
713 ///Returns a reference to the NodeMap of distances.
714 ///\pre Either \ref run() or \ref init() must
715 ///be called before using this function.
716 const DistMap &distMap() const { return *_dist;}
718 ///Returns a reference to the %DFS arc-tree map.
720 ///Returns a reference to the NodeMap of the arcs of the
722 ///\pre Either \ref run() or \ref init()
723 ///must be called before using this function.
724 const PredMap &predMap() const { return *_pred;}
726 ///Checks if a node is reachable from the root.
728 ///Returns \c true if \c v is reachable from the root(s).
729 ///\warning The source nodes are inditated as unreachable.
730 ///\pre Either \ref run() or \ref start()
731 ///must be called before using this function.
733 bool reached(Node v) { return (*_reached)[v]; }
738 ///Default traits class of Dfs function.
740 ///Default traits class of Dfs function.
741 ///\tparam GR Digraph type.
743 struct DfsWizardDefaultTraits
745 ///The digraph type the algorithm runs on.
747 ///\brief The type of the map that stores the last
748 ///arcs of the %DFS paths.
750 ///The type of the map that stores the last
751 ///arcs of the %DFS paths.
752 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
754 typedef NullMap<typename Digraph::Node,typename GR::Arc> PredMap;
755 ///Instantiates a PredMap.
757 ///This function instantiates a \ref PredMap.
758 ///\param g is the digraph, to which we would like to define the PredMap.
759 ///\todo The digraph alone may be insufficient to initialize
761 static PredMap *createPredMap(const GR &g)
763 static PredMap *createPredMap(const GR &)
766 return new PredMap();
769 ///The type of the map that indicates which nodes are processed.
771 ///The type of the map that indicates which nodes are processed.
772 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
773 ///\todo named parameter to set this type, function to read and write.
774 typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
775 ///Instantiates a ProcessedMap.
777 ///This function instantiates a \ref ProcessedMap.
778 ///\param g is the digraph, to which
779 ///we would like to define the \ref ProcessedMap
781 static ProcessedMap *createProcessedMap(const GR &g)
783 static ProcessedMap *createProcessedMap(const GR &)
786 return new ProcessedMap();
788 ///The type of the map that indicates which nodes are reached.
790 ///The type of the map that indicates which nodes are reached.
791 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
792 ///\todo named parameter to set this type, function to read and write.
793 typedef typename Digraph::template NodeMap<bool> ReachedMap;
794 ///Instantiates a ReachedMap.
796 ///This function instantiates a \ref ReachedMap.
797 ///\param G is the digraph, to which
798 ///we would like to define the \ref ReachedMap.
799 static ReachedMap *createReachedMap(const GR &G)
801 return new ReachedMap(G);
803 ///The type of the map that stores the dists of the nodes.
805 ///The type of the map that stores the dists of the nodes.
806 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
808 typedef NullMap<typename Digraph::Node,int> DistMap;
809 ///Instantiates a DistMap.
811 ///This function instantiates a \ref DistMap.
812 ///\param g is the digraph, to which we would like to define
815 static DistMap *createDistMap(const GR &g)
817 static DistMap *createDistMap(const GR &)
820 return new DistMap();
824 /// Default traits used by \ref DfsWizard
826 /// To make it easier to use Dfs algorithm
827 ///we have created a wizard class.
828 /// This \ref DfsWizard class needs default traits,
829 ///as well as the \ref Dfs class.
830 /// The \ref DfsWizardBase is a class to be the default traits of the
831 /// \ref DfsWizard class.
833 class DfsWizardBase : public DfsWizardDefaultTraits<GR>
836 typedef DfsWizardDefaultTraits<GR> Base;
838 /// Type of the nodes in the digraph.
839 typedef typename Base::Digraph::Node Node;
841 /// Pointer to the underlying digraph.
843 ///Pointer to the map of reached nodes.
845 ///Pointer to the map of processed nodes.
847 ///Pointer to the map of predecessors arcs.
849 ///Pointer to the map of distances.
851 ///Pointer to the source node.
857 /// This constructor does not require parameters, therefore it initiates
858 /// all of the attributes to default values (0, INVALID).
859 DfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0),
860 _dist(0), _source(INVALID) {}
864 /// This constructor requires some parameters,
865 /// listed in the parameters list.
866 /// Others are initiated to 0.
867 /// \param g is the initial value of \ref _g
868 /// \param s is the initial value of \ref _source
869 DfsWizardBase(const GR &g, Node s=INVALID) :
870 _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
871 _reached(0), _processed(0), _pred(0), _dist(0), _source(s) {}
875 /// A class to make the usage of the Dfs algorithm easier
877 /// This class is created to make it easier to use the Dfs algorithm.
878 /// It uses the functions and features of the plain \ref Dfs,
879 /// but it is much simpler to use it.
881 /// Simplicity means that the way to change the types defined
882 /// in the traits class is based on functions that returns the new class
883 /// and not on templatable built-in classes.
884 /// When using the plain \ref Dfs
885 /// the new class with the modified type comes from
886 /// the original class by using the ::
887 /// operator. In the case of \ref DfsWizard only
888 /// a function have to be called and it will
889 /// return the needed class.
891 /// It does not have own \ref run method. When its \ref run method is called
892 /// it initiates a plain \ref Dfs object, and calls the \ref Dfs::run
895 class DfsWizard : public TR
899 ///The type of the underlying digraph.
900 typedef typename TR::Digraph Digraph;
902 typedef typename Digraph::Node Node;
904 typedef typename Digraph::NodeIt NodeIt;
906 typedef typename Digraph::Arc Arc;
908 typedef typename Digraph::OutArcIt OutArcIt;
910 ///\brief The type of the map that stores
912 typedef typename TR::ReachedMap ReachedMap;
913 ///\brief The type of the map that stores
914 ///the processed nodes
915 typedef typename TR::ProcessedMap ProcessedMap;
916 ///\brief The type of the map that stores the last
917 ///arcs of the %DFS paths.
918 typedef typename TR::PredMap PredMap;
919 ///The type of the map that stores the distances of the nodes.
920 typedef typename TR::DistMap DistMap;
924 DfsWizard() : TR() {}
926 /// Constructor that requires parameters.
928 /// Constructor that requires parameters.
929 /// These parameters will be the default values for the traits class.
930 DfsWizard(const Digraph &g, Node s=INVALID) :
934 DfsWizard(const TR &b) : TR(b) {}
938 ///Runs Dfs algorithm from a given node.
940 ///Runs Dfs algorithm from a given node.
941 ///The node can be given by the \ref source function.
944 if(Base::_source==INVALID) throw UninitializedParameter();
945 Dfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
947 alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
949 alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
951 alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
953 alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
954 alg.run(Base::_source);
957 ///Runs Dfs algorithm from the given node.
959 ///Runs Dfs algorithm from the given node.
960 ///\param s is the given source.
968 struct DefPredMapBase : public Base {
970 static PredMap *createPredMap(const Digraph &) { return 0; };
971 DefPredMapBase(const TR &b) : TR(b) {}
974 ///\brief \ref named-templ-param "Named parameter"
975 ///function for setting PredMap type
977 /// \ref named-templ-param "Named parameter"
978 ///function for setting PredMap type
981 DfsWizard<DefPredMapBase<T> > predMap(const T &t)
983 Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
984 return DfsWizard<DefPredMapBase<T> >(*this);
989 struct DefReachedMapBase : public Base {
990 typedef T ReachedMap;
991 static ReachedMap *createReachedMap(const Digraph &) { return 0; };
992 DefReachedMapBase(const TR &b) : TR(b) {}
995 ///\brief \ref named-templ-param "Named parameter"
996 ///function for setting ReachedMap
998 /// \ref named-templ-param "Named parameter"
999 ///function for setting ReachedMap
1002 DfsWizard<DefReachedMapBase<T> > reachedMap(const T &t)
1004 Base::_reached=reinterpret_cast<void*>(const_cast<T*>(&t));
1005 return DfsWizard<DefReachedMapBase<T> >(*this);
1010 struct DefProcessedMapBase : public Base {
1011 typedef T ProcessedMap;
1012 static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
1013 DefProcessedMapBase(const TR &b) : TR(b) {}
1016 ///\brief \ref named-templ-param "Named parameter"
1017 ///function for setting ProcessedMap
1019 /// \ref named-templ-param "Named parameter"
1020 ///function for setting ProcessedMap
1023 DfsWizard<DefProcessedMapBase<T> > processedMap(const T &t)
1025 Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1026 return DfsWizard<DefProcessedMapBase<T> >(*this);
1030 struct DefDistMapBase : public Base {
1032 static DistMap *createDistMap(const Digraph &) { return 0; };
1033 DefDistMapBase(const TR &b) : TR(b) {}
1036 ///\brief \ref named-templ-param "Named parameter"
1037 ///function for setting DistMap type
1039 /// \ref named-templ-param "Named parameter"
1040 ///function for setting DistMap type
1043 DfsWizard<DefDistMapBase<T> > distMap(const T &t)
1045 Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1046 return DfsWizard<DefDistMapBase<T> >(*this);
1049 /// Sets the source node, from which the Dfs algorithm runs.
1051 /// Sets the source node, from which the Dfs algorithm runs.
1052 /// \param s is the source node.
1053 DfsWizard<TR> &source(Node s)
1061 ///Function type interface for Dfs algorithm.
1064 ///Function type interface for Dfs algorithm.
1066 ///This function also has several
1067 ///\ref named-templ-func-param "named parameters",
1068 ///they are declared as the members of class \ref DfsWizard.
1070 ///example shows how to use these parameters.
1072 /// dfs(g,source).predMap(preds).run();
1074 ///\warning Don't forget to put the \ref DfsWizard::run() "run()"
1075 ///to the end of the parameter list.
1079 DfsWizard<DfsWizardBase<GR> >
1080 dfs(const GR &g,typename GR::Node s=INVALID)
1082 return DfsWizard<DfsWizardBase<GR> >(g,s);
1086 /// \brief Visitor class for dfs.
1088 /// It gives a simple interface for a functional interface for dfs
1089 /// traversal. The traversal on a linear data structure.
1090 template <typename _Digraph>
1092 typedef _Digraph Digraph;
1093 typedef typename Digraph::Arc Arc;
1094 typedef typename Digraph::Node Node;
1095 /// \brief Called when the arc reach a node.
1097 /// It is called when the dfs find an arc which target is not
1099 void discover(const Arc& arc) {}
1100 /// \brief Called when the node reached first time.
1102 /// It is Called when the node reached first time.
1103 void reach(const Node& node) {}
1104 /// \brief Called when we step back on an arc.
1106 /// It is called when the dfs should step back on the arc.
1107 void backtrack(const Arc& arc) {}
1108 /// \brief Called when we step back from the node.
1110 /// It is called when we step back from the node.
1111 void leave(const Node& node) {}
1112 /// \brief Called when the arc examined but target of the arc
1113 /// already discovered.
1115 /// It called when the arc examined but the target of the arc
1116 /// already discovered.
1117 void examine(const Arc& arc) {}
1118 /// \brief Called for the source node of the dfs.
1120 /// It is called for the source node of the dfs.
1121 void start(const Node& node) {}
1122 /// \brief Called when we leave the source node of the dfs.
1124 /// It is called when we leave the source node of the dfs.
1125 void stop(const Node& node) {}
1129 template <typename _Digraph>
1131 typedef _Digraph Digraph;
1132 typedef typename Digraph::Arc Arc;
1133 typedef typename Digraph::Node Node;
1134 void discover(const Arc&) {}
1135 void reach(const Node&) {}
1136 void backtrack(const Arc&) {}
1137 void leave(const Node&) {}
1138 void examine(const Arc&) {}
1139 void start(const Node&) {}
1140 void stop(const Node&) {}
1142 template <typename _Visitor>
1143 struct Constraints {
1144 void constraints() {
1147 visitor.discover(arc);
1148 visitor.reach(node);
1149 visitor.backtrack(arc);
1150 visitor.leave(node);
1151 visitor.examine(arc);
1152 visitor.start(node);
1160 /// \brief Default traits class of DfsVisit class.
1162 /// Default traits class of DfsVisit class.
1163 /// \tparam _Digraph Digraph type.
1164 template<class _Digraph>
1165 struct DfsVisitDefaultTraits {
1167 /// \brief The digraph type the algorithm runs on.
1168 typedef _Digraph Digraph;
1170 /// \brief The type of the map that indicates which nodes are reached.
1172 /// The type of the map that indicates which nodes are reached.
1173 /// It must meet the \ref concepts::WriteMap "WriteMap" concept.
1174 /// \todo named parameter to set this type, function to read and write.
1175 typedef typename Digraph::template NodeMap<bool> ReachedMap;
1177 /// \brief Instantiates a ReachedMap.
1179 /// This function instantiates a \ref ReachedMap.
1180 /// \param digraph is the digraph, to which
1181 /// we would like to define the \ref ReachedMap.
1182 static ReachedMap *createReachedMap(const Digraph &digraph) {
1183 return new ReachedMap(digraph);
1188 /// %DFS Visit algorithm class.
1191 /// This class provides an efficient implementation of the %DFS algorithm
1192 /// with visitor interface.
1194 /// The %DfsVisit class provides an alternative interface to the Dfs
1195 /// class. It works with callback mechanism, the DfsVisit object calls
1196 /// on every dfs event the \c Visitor class member functions.
1198 /// \tparam _Digraph The digraph type the algorithm runs on.
1199 /// The default value is
1200 /// \ref ListDigraph. The value of _Digraph is not used directly by Dfs, it
1201 /// is only passed to \ref DfsDefaultTraits.
1202 /// \tparam _Visitor The Visitor object for the algorithm. The
1203 /// \ref DfsVisitor "DfsVisitor<_Digraph>" is an empty Visitor which
1204 /// does not observe the Dfs events. If you want to observe the dfs
1205 /// events you should implement your own Visitor class.
1206 /// \tparam _Traits Traits class to set various data types used by the
1207 /// algorithm. The default traits class is
1208 /// \ref DfsVisitDefaultTraits "DfsVisitDefaultTraits<_Digraph>".
1209 /// See \ref DfsVisitDefaultTraits for the documentation of
1210 /// a Dfs visit traits class.
1212 /// \author Jacint Szabo, Alpar Juttner and Balazs Dezso
1214 template <typename _Digraph, typename _Visitor, typename _Traits>
1216 template <typename _Digraph = ListDigraph,
1217 typename _Visitor = DfsVisitor<_Digraph>,
1218 typename _Traits = DfsDefaultTraits<_Digraph> >
1223 /// \brief \ref Exception for uninitialized parameters.
1225 /// This error represents problems in the initialization
1226 /// of the parameters of the algorithms.
1227 class UninitializedParameter : public lemon::UninitializedParameter {
1229 virtual const char* what() const throw()
1231 return "lemon::DfsVisit::UninitializedParameter";
1235 typedef _Traits Traits;
1237 typedef typename Traits::Digraph Digraph;
1239 typedef _Visitor Visitor;
1241 ///The type of the map indicating which nodes are reached.
1242 typedef typename Traits::ReachedMap ReachedMap;
1246 typedef typename Digraph::Node Node;
1247 typedef typename Digraph::NodeIt NodeIt;
1248 typedef typename Digraph::Arc Arc;
1249 typedef typename Digraph::OutArcIt OutArcIt;
1251 /// Pointer to the underlying digraph.
1252 const Digraph *_digraph;
1253 /// Pointer to the visitor object.
1255 ///Pointer to the map of reached status of the nodes.
1256 ReachedMap *_reached;
1257 ///Indicates if \ref _reached is locally allocated (\c true) or not.
1260 std::vector<typename Digraph::Arc> _stack;
1263 /// \brief Creates the maps if necessary.
1265 /// Creates the maps if necessary.
1266 void create_maps() {
1268 local_reached = true;
1269 _reached = Traits::createReachedMap(*_digraph);
1279 typedef DfsVisit Create;
1281 /// \name Named template parameters
1285 struct DefReachedMapTraits : public Traits {
1286 typedef T ReachedMap;
1287 static ReachedMap *createReachedMap(const Digraph &digraph) {
1288 throw UninitializedParameter();
1291 /// \brief \ref named-templ-param "Named parameter" for setting
1294 /// \ref named-templ-param "Named parameter" for setting ReachedMap type
1296 struct DefReachedMap : public DfsVisit< Digraph, Visitor,
1297 DefReachedMapTraits<T> > {
1298 typedef DfsVisit< Digraph, Visitor, DefReachedMapTraits<T> > Create;
1304 /// \brief Constructor.
1308 /// \param digraph the digraph the algorithm will run on.
1309 /// \param visitor The visitor of the algorithm.
1311 DfsVisit(const Digraph& digraph, Visitor& visitor)
1312 : _digraph(&digraph), _visitor(&visitor),
1313 _reached(0), local_reached(false) {}
1315 /// \brief Destructor.
1319 if(local_reached) delete _reached;
1322 /// \brief Sets the map indicating if a node is reached.
1324 /// Sets the map indicating if a node is reached.
1325 /// If you don't use this function before calling \ref run(),
1326 /// it will allocate one. The destuctor deallocates this
1327 /// automatically allocated map, of course.
1328 /// \return <tt> (*this) </tt>
1329 DfsVisit &reachedMap(ReachedMap &m) {
1332 local_reached=false;
1339 /// \name Execution control
1340 /// The simplest way to execute the algorithm is to use
1341 /// one of the member functions called \c run(...).
1343 /// If you need more control on the execution,
1344 /// first you must call \ref init(), then you can adda source node
1345 /// with \ref addSource().
1346 /// Finally \ref start() will perform the actual path
1350 /// \brief Initializes the internal data structures.
1352 /// Initializes the internal data structures.
1356 _stack.resize(countNodes(*_digraph));
1358 for (NodeIt u(*_digraph) ; u != INVALID ; ++u) {
1359 _reached->set(u, false);
1363 /// \brief Adds a new source node.
1365 /// Adds a new source node to the set of nodes to be processed.
1366 void addSource(Node s) {
1367 if(!(*_reached)[s]) {
1368 _reached->set(s,true);
1372 _digraph->firstOut(e, s);
1374 _stack[++_stack_head] = e;
1381 /// \brief Processes the next arc.
1383 /// Processes the next arc.
1385 /// \return The processed arc.
1387 /// \pre The stack must not be empty!
1388 Arc processNextArc() {
1389 Arc e = _stack[_stack_head];
1390 Node m = _digraph->target(e);
1391 if(!(*_reached)[m]) {
1392 _visitor->discover(e);
1394 _reached->set(m, true);
1395 _digraph->firstOut(_stack[++_stack_head], m);
1397 _visitor->examine(e);
1398 m = _digraph->source(e);
1399 _digraph->nextOut(_stack[_stack_head]);
1401 while (_stack_head>=0 && _stack[_stack_head] == INVALID) {
1404 if (_stack_head >= 0) {
1405 _visitor->backtrack(_stack[_stack_head]);
1406 m = _digraph->source(_stack[_stack_head]);
1407 _digraph->nextOut(_stack[_stack_head]);
1415 /// \brief Next arc to be processed.
1417 /// Next arc to be processed.
1419 /// \return The next arc to be processed or INVALID if the stack is
1422 return _stack_head >= 0 ? _stack[_stack_head] : INVALID;
1425 /// \brief Returns \c false if there are nodes
1426 /// to be processed in the queue
1428 /// Returns \c false if there are nodes
1429 /// to be processed in the queue
1430 bool emptyQueue() { return _stack_head < 0; }
1432 /// \brief Returns the number of the nodes to be processed.
1434 /// Returns the number of the nodes to be processed in the queue.
1435 int queueSize() { return _stack_head + 1; }
1437 /// \brief Executes the algorithm.
1439 /// Executes the algorithm.
1441 /// \pre init() must be called and at least one node should be added
1442 /// with addSource() before using this function.
1444 while ( !emptyQueue() ) processNextArc();
1447 /// \brief Executes the algorithm until \c dest is reached.
1449 /// Executes the algorithm until \c dest is reached.
1451 /// \pre init() must be called and at least one node should be added
1452 /// with addSource() before using this function.
1453 void start(Node dest) {
1454 while ( !emptyQueue() && _digraph->target(_stack[_stack_head]) != dest )
1458 /// \brief Executes the algorithm until a condition is met.
1460 /// Executes the algorithm until a condition is met.
1462 /// \pre init() must be called and at least one node should be added
1463 /// with addSource() before using this function.
1465 /// \param em must be a bool (or convertible) arc map. The algorithm
1466 /// will stop when it reaches an arc \c e with <tt>em[e]</tt> true.
1468 ///\return The reached arc \c e with <tt>em[e]</tt> true or
1469 ///\c INVALID if no such arc was found.
1471 /// \warning Contrary to \ref Bfs and \ref Dijkstra, \c em is an arc map,
1473 template <typename EM>
1474 Arc start(const EM &em) {
1475 while ( !emptyQueue() && !em[_stack[_stack_head]] )
1477 return emptyQueue() ? INVALID : _stack[_stack_head];
1480 /// \brief Runs %DFSVisit algorithm from node \c s.
1482 /// This method runs the %DFS algorithm from a root node \c s.
1483 /// \note d.run(s) is just a shortcut of the following code.
1495 /// \brief Runs %DFSVisit algorithm to visit all nodes in the digraph.
1497 /// This method runs the %DFS algorithm in order to
1498 /// compute the %DFS path to each node. The algorithm computes
1499 /// - The %DFS tree.
1500 /// - The distance of each node from the root in the %DFS tree.
1502 ///\note d.run() is just a shortcut of the following code.
1505 /// for (NodeIt it(digraph); it != INVALID; ++it) {
1506 /// if (!d.reached(it)) {
1507 /// d.addSource(it);
1514 for (NodeIt it(*_digraph); it != INVALID; ++it) {
1523 /// \name Query Functions
1524 /// The result of the %DFS algorithm can be obtained using these
1526 /// Before the use of these functions,
1527 /// either run() or start() must be called.
1529 /// \brief Checks if a node is reachable from the root.
1531 /// Returns \c true if \c v is reachable from the root(s).
1532 /// \warning The source nodes are inditated as unreachable.
1533 /// \pre Either \ref run() or \ref start()
1534 /// must be called before using this function.
1536 bool reached(Node v) { return (*_reached)[v]; }
1541 } //END OF NAMESPACE LEMON