2 * lemon/dfs.h - Part of LEMON, a generic C++ optimization library
4 * Copyright (C) 2005 Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
5 * (Egervary Research Group on Combinatorial Optimization, EGRES).
7 * Permission to use, modify and distribute this software is granted
8 * provided that this copyright notice appears in all copies. For
9 * precise terms see the accompanying LICENSE file.
11 * This software is provided "AS IS" with no warranty of any kind,
12 * express or implied, and with no claim as to its suitability for any
22 ///\brief Dfs algorithm.
24 #include <lemon/list_graph.h>
25 #include <lemon/graph_utils.h>
26 #include <lemon/invalid.h>
27 #include <lemon/error.h>
28 #include <lemon/maps.h>
30 #include <lemon/concept_check.h>
35 ///Default traits class of Dfs class.
37 ///Default traits class of Dfs class.
38 ///\param GR Graph type.
40 struct DfsDefaultTraits
42 ///The graph type the algorithm runs on.
44 ///\brief The type of the map that stores the last
45 ///edges of the %DFS paths.
47 ///The type of the map that stores the last
48 ///edges of the %DFS paths.
49 ///It must meet the \ref concept::WriteMap "WriteMap" concept.
51 typedef typename Graph::template NodeMap<typename GR::Edge> PredMap;
52 ///Instantiates a PredMap.
54 ///This function instantiates a \ref PredMap.
55 ///\param G is the graph, to which we would like to define the PredMap.
56 ///\todo The graph alone may be insufficient to initialize
57 static PredMap *createPredMap(const GR &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 concept::WriteMap "WriteMap" concept.
66 ///\todo named parameter to set this type, function to read and write.
67 typedef NullMap<typename Graph::Node,bool> ProcessedMap;
68 ///Instantiates a ProcessedMap.
70 ///This function instantiates a \ref ProcessedMap.
71 ///\param g is the graph, to which
72 ///we would like to define the \ref ProcessedMap
74 static ProcessedMap *createProcessedMap(const GR &g)
76 static ProcessedMap *createProcessedMap(const GR &)
79 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 concept::WriteMap "WriteMap" concept.
85 ///\todo named parameter to set this type, function to read and write.
86 typedef typename Graph::template NodeMap<bool> ReachedMap;
87 ///Instantiates a ReachedMap.
89 ///This function instantiates a \ref ReachedMap.
90 ///\param G is the graph, to which
91 ///we would like to define the \ref ReachedMap.
92 static ReachedMap *createReachedMap(const GR &G)
94 return new ReachedMap(G);
96 ///The type of the map that stores the dists of the nodes.
98 ///The type of the map that stores the dists of the nodes.
99 ///It must meet the \ref concept::WriteMap "WriteMap" concept.
101 typedef typename Graph::template NodeMap<int> DistMap;
102 ///Instantiates a DistMap.
104 ///This function instantiates a \ref DistMap.
105 ///\param G is the graph, to which we would like to define the \ref DistMap
106 static DistMap *createDistMap(const GR &G)
108 return new DistMap(G);
112 ///%DFS algorithm class.
115 ///This class provides an efficient implementation of the %DFS algorithm.
117 ///\param GR The graph type the algorithm runs on. The default value is
118 ///\ref ListGraph. The value of GR is not used directly by Dfs, it
119 ///is only passed to \ref DfsDefaultTraits.
120 ///\param TR Traits class to set various data types used by the algorithm.
121 ///The default traits class is
122 ///\ref DfsDefaultTraits "DfsDefaultTraits<GR>".
123 ///See \ref DfsDefaultTraits for the documentation of
124 ///a Dfs traits class.
126 ///\author Jacint Szabo and Alpar Juttner
128 template <typename GR,
131 template <typename GR=ListGraph,
132 typename TR=DfsDefaultTraits<GR> >
137 * \brief \ref Exception for uninitialized parameters.
139 * This error represents problems in the initialization
140 * of the parameters of the algorithms.
142 class UninitializedParameter : public lemon::UninitializedParameter {
144 virtual const char* exceptionName() const {
145 return "lemon::Dfs::UninitializedParameter";
150 ///The type of the underlying graph.
151 typedef typename TR::Graph Graph;
153 typedef typename Graph::Node Node;
155 typedef typename Graph::NodeIt NodeIt;
157 typedef typename Graph::Edge Edge;
159 typedef typename Graph::OutEdgeIt OutEdgeIt;
161 ///\brief The type of the map that stores the last
162 ///edges of the %DFS paths.
163 typedef typename TR::PredMap PredMap;
164 ///The type of the map indicating which nodes are reached.
165 typedef typename TR::ReachedMap ReachedMap;
166 ///The type of the map indicating which nodes are processed.
167 typedef typename TR::ProcessedMap ProcessedMap;
168 ///The type of the map that stores the dists of the nodes.
169 typedef typename TR::DistMap DistMap;
171 /// Pointer to the underlying graph.
173 ///Pointer to the map of predecessors edges.
175 ///Indicates if \ref _pred is locally allocated (\c true) or not.
177 ///Pointer to the map of distances.
179 ///Indicates if \ref _dist is locally allocated (\c true) or not.
181 ///Pointer to the map of reached status of the nodes.
182 ReachedMap *_reached;
183 ///Indicates if \ref _reached is locally allocated (\c true) or not.
185 ///Pointer to the map of processed status of the nodes.
186 ProcessedMap *_processed;
187 ///Indicates if \ref _processed is locally allocated (\c true) or not.
188 bool local_processed;
190 std::vector<typename Graph::OutEdgeIt> _stack;
193 ///Creates the maps if necessary.
195 ///\todo Error if \c G are \c NULL.
196 ///\todo Better memory allocation (instead of new).
201 _pred = Traits::createPredMap(*G);
205 _dist = Traits::createDistMap(*G);
208 local_reached = true;
209 _reached = Traits::createReachedMap(*G);
212 local_processed = true;
213 _processed = Traits::createProcessedMap(*G);
225 ///\name Named template parameters
230 struct DefPredMapTraits : public Traits {
232 static PredMap *createPredMap(const Graph &G)
234 throw UninitializedParameter();
237 ///\ref named-templ-param "Named parameter" for setting PredMap type
239 ///\ref named-templ-param "Named parameter" for setting PredMap type
242 struct DefPredMap : public Dfs<Graph, DefPredMapTraits<T> > {
243 typedef Dfs<Graph, DefPredMapTraits<T> > Create;
248 struct DefDistMapTraits : public Traits {
250 static DistMap *createDistMap(const Graph &G)
252 throw UninitializedParameter();
255 ///\ref named-templ-param "Named parameter" for setting DistMap type
257 ///\ref named-templ-param "Named parameter" for setting DistMap type
261 typedef Dfs<Graph, DefDistMapTraits<T> > Create;
265 struct DefReachedMapTraits : public Traits {
266 typedef T ReachedMap;
267 static ReachedMap *createReachedMap(const Graph &G)
269 throw UninitializedParameter();
272 ///\ref named-templ-param "Named parameter" for setting ReachedMap type
274 ///\ref named-templ-param "Named parameter" for setting ReachedMap type
277 struct DefReachedMap : public Dfs< Graph, DefReachedMapTraits<T> > {
278 typedef Dfs< Graph, DefReachedMapTraits<T> > Create;
282 struct DefProcessedMapTraits : public Traits {
283 typedef T ProcessedMap;
284 static ProcessedMap *createProcessedMap(const Graph &G)
286 throw UninitializedParameter();
289 ///\ref named-templ-param "Named parameter" for setting ProcessedMap type
291 ///\ref named-templ-param "Named parameter" for setting ProcessedMap type
294 struct DefProcessedMap : public Dfs< Graph, DefProcessedMapTraits<T> > {
295 typedef Dfs< Graph, DefProcessedMapTraits<T> > Create;
298 struct DefGraphProcessedMapTraits : public Traits {
299 typedef typename Graph::template NodeMap<bool> ProcessedMap;
300 static ProcessedMap *createProcessedMap(const Graph &G)
302 return new ProcessedMap(G);
305 ///\brief \ref named-templ-param "Named parameter"
306 ///for setting the ProcessedMap type to be Graph::NodeMap<bool>.
308 ///\ref named-templ-param "Named parameter"
309 ///for setting the ProcessedMap type to be Graph::NodeMap<bool>.
310 ///If you don't set it explicitely, it will be automatically allocated.
312 class DefProcessedMapToBeDefaultMap :
313 public Dfs< Graph, DefGraphProcessedMapTraits> {
314 typedef Dfs< Graph, DefGraphProcessedMapTraits> Create;
323 ///\param _G the graph the algorithm will run on.
325 Dfs(const Graph& _G) :
327 _pred(NULL), local_pred(false),
328 _dist(NULL), local_dist(false),
329 _reached(NULL), local_reached(false),
330 _processed(NULL), local_processed(false)
336 if(local_pred) delete _pred;
337 if(local_dist) delete _dist;
338 if(local_reached) delete _reached;
339 if(local_processed) delete _processed;
342 ///Sets the map storing the predecessor edges.
344 ///Sets the map storing the predecessor edges.
345 ///If you don't use this function before calling \ref run(),
346 ///it will allocate one. The destuctor deallocates this
347 ///automatically allocated map, of course.
348 ///\return <tt> (*this) </tt>
349 Dfs &predMap(PredMap &m)
359 ///Sets the map storing the distances calculated by the algorithm.
361 ///Sets the map storing the distances calculated by the algorithm.
362 ///If you don't use this function before calling \ref run(),
363 ///it will allocate one. The destuctor deallocates this
364 ///automatically allocated map, of course.
365 ///\return <tt> (*this) </tt>
366 Dfs &distMap(DistMap &m)
376 ///Sets the map indicating if a node is reached.
378 ///Sets the map indicating if a node is reached.
379 ///If you don't use this function before calling \ref run(),
380 ///it will allocate one. The destuctor deallocates this
381 ///automatically allocated map, of course.
382 ///\return <tt> (*this) </tt>
383 Dfs &reachedMap(ReachedMap &m)
393 ///Sets the map indicating if a node is processed.
395 ///Sets the map indicating if a node is processed.
396 ///If you don't use this function before calling \ref run(),
397 ///it will allocate one. The destuctor deallocates this
398 ///automatically allocated map, of course.
399 ///\return <tt> (*this) </tt>
400 Dfs &processedMap(ProcessedMap &m)
402 if(local_processed) {
404 local_processed=false;
411 ///\name Execution control
412 ///The simplest way to execute the algorithm is to use
413 ///one of the member functions called \c run(...).
415 ///If you need more control on the execution,
416 ///first you must call \ref init(), then you can add several source nodes
417 ///with \ref addSource().
418 ///Finally \ref start() will perform the actual path
423 ///Initializes the internal data structures.
425 ///Initializes the internal data structures.
430 _stack.resize(countNodes(*G));
432 for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
433 _pred->set(u,INVALID);
434 // _predNode->set(u,INVALID);
435 _reached->set(u,false);
436 _processed->set(u,false);
440 ///Adds a new source node.
442 ///Adds a new source node to the set of nodes to be processed.
444 ///\bug dists are wrong (or at least strange) in case of multiple sources.
445 void addSource(Node s)
449 _reached->set(s,true);
450 _pred->set(s,INVALID);
453 _stack[++_stack_head]=e;
454 _dist->set(s,_stack_head);
457 _processed->set(s,true);
463 ///Processes the next edge.
465 ///Processes the next edge.
467 ///\return The processed edge.
469 ///\pre The stack must not be empty!
470 Edge processNextEdge()
473 Edge e=_stack[_stack_head];
474 if(!(*_reached)[m=G->target(e)]) {
476 _reached->set(m,true);
478 _stack[_stack_head] = OutEdgeIt(*G, m);
479 _dist->set(m,_stack_head);
483 ++_stack[_stack_head];
485 while(_stack_head>=0 && _stack[_stack_head]==INVALID) {
486 _processed->set(m,true);
489 m=G->source(_stack[_stack_head]);
490 ++_stack[_stack_head];
495 ///Next edge to be processed.
497 ///Next edge to be processed.
499 ///\return The next edge to be processed or INVALID if the stack is
503 return _stack_head>=0?_stack[_stack_head]:INVALID;
506 ///\brief Returns \c false if there are nodes
507 ///to be processed in the queue
509 ///Returns \c false if there are nodes
510 ///to be processed in the queue
512 ///\todo This should be called emptyStack() or some "neutral" name.
513 bool emptyQueue() { return _stack_head<0; }
514 ///Returns the number of the nodes to be processed.
516 ///Returns the number of the nodes to be processed in the queue.
518 ///\todo This should be called stackSize() or some "neutral" name.
519 int queueSize() { return _stack_head+1; }
521 ///Executes the algorithm.
523 ///Executes the algorithm.
525 ///\pre init() must be called and at least one node should be added
526 ///with addSource() before using this function.
528 ///This method runs the %DFS algorithm from the root node(s)
531 ///%DFS path to each node. The algorithm computes
533 ///- The distance of each node from the root(s) in the %DFS tree.
537 while ( !emptyQueue() ) processNextEdge();
540 ///Executes the algorithm until \c dest is reached.
542 ///Executes the algorithm until \c dest is reached.
544 ///\pre init() must be called and at least one node should be added
545 ///with addSource() before using this function.
547 ///This method runs the %DFS algorithm from the root node(s)
550 ///%DFS path to \c dest. The algorithm computes
551 ///- The %DFS path to \c dest.
552 ///- The distance of \c dest from the root(s) in the %DFS tree.
554 void start(Node dest)
556 while ( !emptyQueue() && G->target(_stack[_stack_head])!=dest )
560 ///Executes the algorithm until a condition is met.
562 ///Executes the algorithm until a condition is met.
564 ///\pre init() must be called and at least one node should be added
565 ///with addSource() before using this function.
567 ///\param nm must be a bool (or convertible) edge map. The algorithm
568 ///will stop when it reaches an edge \c e with <tt>nm[e]==true</tt>.
570 ///\warning Contrary to \ref Dfs and \ref Dijkstra, \c em is an edge map,
573 void start(const EM &em)
575 while ( !emptyQueue() && !em[_stack[_stack_head]] ) processNextEdge();
578 ///Runs %DFS algorithm from node \c s.
580 ///This method runs the %DFS algorithm from a root node \c s
583 ///%DFS path to each node. The algorithm computes
585 ///- The distance of each node from the root in the %DFS tree.
587 ///\note d.run(s) is just a shortcut of the following code.
599 ///Finds the %DFS path between \c s and \c t.
601 ///Finds the %DFS path between \c s and \c t.
603 ///\return The length of the %DFS s---t path if there exists one,
605 ///\note Apart from the return value, d.run(s,t) is
606 ///just a shortcut of the following code.
612 int run(Node s,Node t) {
616 return reached(t)?_stack_head+1:0;
621 ///\name Query Functions
622 ///The result of the %DFS algorithm can be obtained using these
624 ///Before the use of these functions,
625 ///either run() or start() must be called.
629 ///Copies the path to \c t on the DFS tree into \c p
631 ///This function copies the path to \c t on the DFS tree into \c p.
632 ///If \c t is a source itself or unreachable, then it does not
634 ///\todo Is this the right way to handle unreachable nodes?
636 ///\return Returns \c true if a path to \c t was actually copied to \c p,
637 ///\c false otherwise.
640 bool getPath(P &p,Node t)
644 typename P::Builder b(p);
645 for(b.setStartNode(t);pred(t)!=INVALID;t=predNode(t))
646 b.pushFront(pred(t));
653 ///The distance of a node from the root(s).
655 ///Returns the distance of a node from the root(s).
656 ///\pre \ref run() must be called before using this function.
657 ///\warning If node \c v is unreachable from the root(s) then the return value
658 ///of this funcion is undefined.
659 int dist(Node v) const { return (*_dist)[v]; }
661 ///Returns the 'previous edge' of the %DFS tree.
663 ///For a node \c v it returns the 'previous edge'
665 ///i.e. it returns the last edge of a %DFS path from the root(s) to \c
666 ///v. It is \ref INVALID
667 ///if \c v is unreachable from the root(s) or \c v is a root. The
668 ///%DFS tree used here is equal to the %DFS tree used in
670 ///\pre Either \ref run() or \ref start() must be called before using
672 ///\todo predEdge could be a better name.
673 Edge pred(Node v) const { return (*_pred)[v];}
675 ///Returns the 'previous node' of the %DFS tree.
677 ///For a node \c v it returns the 'previous node'
679 ///i.e. it returns the last but one node from a %DFS path from the
681 ///It is INVALID if \c v is unreachable from the root(s) or
682 ///if \c v itself a root.
683 ///The %DFS tree used here is equal to the %DFS
684 ///tree used in \ref pred().
685 ///\pre Either \ref run() or \ref start() must be called before
686 ///using this function.
687 Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
688 G->source((*_pred)[v]); }
690 ///Returns a reference to the NodeMap of distances.
692 ///Returns a reference to the NodeMap of distances.
693 ///\pre Either \ref run() or \ref init() must
694 ///be called before using this function.
695 const DistMap &distMap() const { return *_dist;}
697 ///Returns a reference to the %DFS edge-tree map.
699 ///Returns a reference to the NodeMap of the edges of the
701 ///\pre Either \ref run() or \ref init()
702 ///must be called before using this function.
703 const PredMap &predMap() const { return *_pred;}
705 ///Checks if a node is reachable from the root.
707 ///Returns \c true if \c v is reachable from the root(s).
708 ///\warning The source nodes are inditated as unreachable.
709 ///\pre Either \ref run() or \ref start()
710 ///must be called before using this function.
712 bool reached(Node v) { return (*_reached)[v]; }
717 ///Default traits class of Dfs function.
719 ///Default traits class of Dfs function.
720 ///\param GR Graph type.
722 struct DfsWizardDefaultTraits
724 ///The graph type the algorithm runs on.
726 ///\brief The type of the map that stores the last
727 ///edges of the %DFS paths.
729 ///The type of the map that stores the last
730 ///edges of the %DFS paths.
731 ///It must meet the \ref concept::WriteMap "WriteMap" concept.
733 typedef NullMap<typename Graph::Node,typename GR::Edge> PredMap;
734 ///Instantiates a PredMap.
736 ///This function instantiates a \ref PredMap.
737 ///\param g is the graph, to which we would like to define the PredMap.
738 ///\todo The graph alone may be insufficient to initialize
740 static PredMap *createPredMap(const GR &g)
742 static PredMap *createPredMap(const GR &)
745 return new PredMap();
748 ///The type of the map that indicates which nodes are processed.
750 ///The type of the map that indicates which nodes are processed.
751 ///It must meet the \ref concept::WriteMap "WriteMap" concept.
752 ///\todo named parameter to set this type, function to read and write.
753 typedef NullMap<typename Graph::Node,bool> ProcessedMap;
754 ///Instantiates a ProcessedMap.
756 ///This function instantiates a \ref ProcessedMap.
757 ///\param g is the graph, to which
758 ///we would like to define the \ref ProcessedMap
760 static ProcessedMap *createProcessedMap(const GR &g)
762 static ProcessedMap *createProcessedMap(const GR &)
765 return new ProcessedMap();
767 ///The type of the map that indicates which nodes are reached.
769 ///The type of the map that indicates which nodes are reached.
770 ///It must meet the \ref concept::WriteMap "WriteMap" concept.
771 ///\todo named parameter to set this type, function to read and write.
772 typedef typename Graph::template NodeMap<bool> ReachedMap;
773 ///Instantiates a ReachedMap.
775 ///This function instantiates a \ref ReachedMap.
776 ///\param G is the graph, to which
777 ///we would like to define the \ref ReachedMap.
778 static ReachedMap *createReachedMap(const GR &G)
780 return new ReachedMap(G);
782 ///The type of the map that stores the dists of the nodes.
784 ///The type of the map that stores the dists of the nodes.
785 ///It must meet the \ref concept::WriteMap "WriteMap" concept.
787 typedef NullMap<typename Graph::Node,int> DistMap;
788 ///Instantiates a DistMap.
790 ///This function instantiates a \ref DistMap.
791 ///\param g is the graph, to which we would like to define the \ref DistMap
793 static DistMap *createDistMap(const GR &g)
795 static DistMap *createDistMap(const GR &)
798 return new DistMap();
802 /// Default traits used by \ref DfsWizard
804 /// To make it easier to use Dfs algorithm
805 ///we have created a wizard class.
806 /// This \ref DfsWizard class needs default traits,
807 ///as well as the \ref Dfs class.
808 /// The \ref DfsWizardBase is a class to be the default traits of the
809 /// \ref DfsWizard class.
811 class DfsWizardBase : public DfsWizardDefaultTraits<GR>
814 typedef DfsWizardDefaultTraits<GR> Base;
816 /// Type of the nodes in the graph.
817 typedef typename Base::Graph::Node Node;
819 /// Pointer to the underlying graph.
821 ///Pointer to the map of reached nodes.
823 ///Pointer to the map of processed nodes.
825 ///Pointer to the map of predecessors edges.
827 ///Pointer to the map of distances.
829 ///Pointer to the source node.
835 /// This constructor does not require parameters, therefore it initiates
836 /// all of the attributes to default values (0, INVALID).
837 DfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0),
838 _dist(0), _source(INVALID) {}
842 /// This constructor requires some parameters,
843 /// listed in the parameters list.
844 /// Others are initiated to 0.
845 /// \param g is the initial value of \ref _g
846 /// \param s is the initial value of \ref _source
847 DfsWizardBase(const GR &g, Node s=INVALID) :
848 _g((void *)&g), _reached(0), _processed(0), _pred(0),
849 _dist(0), _source(s) {}
853 /// A class to make the usage of the Dfs algorithm easier
855 /// This class is created to make it easier to use the Dfs algorithm.
856 /// It uses the functions and features of the plain \ref Dfs,
857 /// but it is much simpler to use it.
859 /// Simplicity means that the way to change the types defined
860 /// in the traits class is based on functions that returns the new class
861 /// and not on templatable built-in classes.
862 /// When using the plain \ref Dfs
863 /// the new class with the modified type comes from
864 /// the original class by using the ::
865 /// operator. In the case of \ref DfsWizard only
866 /// a function have to be called and it will
867 /// return the needed class.
869 /// It does not have own \ref run method. When its \ref run method is called
870 /// it initiates a plain \ref Dfs object, and calls the \ref Dfs::run
873 class DfsWizard : public TR
877 ///The type of the underlying graph.
878 typedef typename TR::Graph Graph;
880 typedef typename Graph::Node Node;
882 typedef typename Graph::NodeIt NodeIt;
884 typedef typename Graph::Edge Edge;
886 typedef typename Graph::OutEdgeIt OutEdgeIt;
888 ///\brief The type of the map that stores
890 typedef typename TR::ReachedMap ReachedMap;
891 ///\brief The type of the map that stores
892 ///the processed nodes
893 typedef typename TR::ProcessedMap ProcessedMap;
894 ///\brief The type of the map that stores the last
895 ///edges of the %DFS paths.
896 typedef typename TR::PredMap PredMap;
897 ///The type of the map that stores the distances of the nodes.
898 typedef typename TR::DistMap DistMap;
902 DfsWizard() : TR() {}
904 /// Constructor that requires parameters.
906 /// Constructor that requires parameters.
907 /// These parameters will be the default values for the traits class.
908 DfsWizard(const Graph &g, Node s=INVALID) :
912 DfsWizard(const TR &b) : TR(b) {}
916 ///Runs Dfs algorithm from a given node.
918 ///Runs Dfs algorithm from a given node.
919 ///The node can be given by the \ref source function.
922 if(Base::_source==INVALID) throw UninitializedParameter();
923 Dfs<Graph,TR> alg(*(Graph*)Base::_g);
924 if(Base::_reached) alg.reachedMap(*(ReachedMap*)Base::_reached);
925 if(Base::_processed) alg.processedMap(*(ProcessedMap*)Base::_processed);
926 if(Base::_pred) alg.predMap(*(PredMap*)Base::_pred);
927 if(Base::_dist) alg.distMap(*(DistMap*)Base::_dist);
928 alg.run(Base::_source);
931 ///Runs Dfs algorithm from the given node.
933 ///Runs Dfs algorithm from the given node.
934 ///\param s is the given source.
942 struct DefPredMapBase : public Base {
944 static PredMap *createPredMap(const Graph &) { return 0; };
945 DefPredMapBase(const TR &b) : TR(b) {}
948 ///\brief \ref named-templ-param "Named parameter"
949 ///function for setting PredMap type
951 /// \ref named-templ-param "Named parameter"
952 ///function for setting PredMap type
955 DfsWizard<DefPredMapBase<T> > predMap(const T &t)
957 Base::_pred=(void *)&t;
958 return DfsWizard<DefPredMapBase<T> >(*this);
963 struct DefReachedMapBase : public Base {
964 typedef T ReachedMap;
965 static ReachedMap *createReachedMap(const Graph &) { return 0; };
966 DefReachedMapBase(const TR &b) : TR(b) {}
969 ///\brief \ref named-templ-param "Named parameter"
970 ///function for setting ReachedMap
972 /// \ref named-templ-param "Named parameter"
973 ///function for setting ReachedMap
976 DfsWizard<DefReachedMapBase<T> > reachedMap(const T &t)
978 Base::_pred=(void *)&t;
979 return DfsWizard<DefReachedMapBase<T> >(*this);
984 struct DefProcessedMapBase : public Base {
985 typedef T ProcessedMap;
986 static ProcessedMap *createProcessedMap(const Graph &) { return 0; };
987 DefProcessedMapBase(const TR &b) : TR(b) {}
990 ///\brief \ref named-templ-param "Named parameter"
991 ///function for setting ProcessedMap
993 /// \ref named-templ-param "Named parameter"
994 ///function for setting ProcessedMap
997 DfsWizard<DefProcessedMapBase<T> > processedMap(const T &t)
999 Base::_pred=(void *)&t;
1000 return DfsWizard<DefProcessedMapBase<T> >(*this);
1004 struct DefDistMapBase : public Base {
1006 static DistMap *createDistMap(const Graph &) { return 0; };
1007 DefDistMapBase(const TR &b) : TR(b) {}
1010 ///\brief \ref named-templ-param "Named parameter"
1011 ///function for setting DistMap type
1013 /// \ref named-templ-param "Named parameter"
1014 ///function for setting DistMap type
1017 DfsWizard<DefDistMapBase<T> > distMap(const T &t)
1019 Base::_dist=(void *)&t;
1020 return DfsWizard<DefDistMapBase<T> >(*this);
1023 /// Sets the source node, from which the Dfs algorithm runs.
1025 /// Sets the source node, from which the Dfs algorithm runs.
1026 /// \param s is the source node.
1027 DfsWizard<TR> &source(Node s)
1035 ///Function type interface for Dfs algorithm.
1037 /// \ingroup flowalgs
1038 ///Function type interface for Dfs algorithm.
1040 ///This function also has several
1041 ///\ref named-templ-func-param "named parameters",
1042 ///they are declared as the members of class \ref DfsWizard.
1044 ///example shows how to use these parameters.
1046 /// dfs(g,source).predMap(preds).run();
1048 ///\warning Don't forget to put the \ref DfsWizard::run() "run()"
1049 ///to the end of the parameter list.
1053 DfsWizard<DfsWizardBase<GR> >
1054 dfs(const GR &g,typename GR::Node s=INVALID)
1056 return DfsWizard<DfsWizardBase<GR> >(g,s);
1059 /// \brief Visitor class for dfs.
1061 /// It gives a simple interface for a functional interface for dfs
1062 /// traversal. The traversal on a linear data structure.
1063 template <typename _Graph>
1065 typedef _Graph Graph;
1066 typedef typename Graph::Edge Edge;
1067 typedef typename Graph::Node Node;
1068 /// \brief Called when the edge reach a node.
1070 /// It is called when the dfs find an edge which target is not
1072 void discover(const Edge& edge) {}
1073 /// \brief Called when the node reached first time.
1075 /// It is Called when the node reached first time.
1076 void reach(const Node& node) {}
1077 /// \brief Called when we step back on an edge.
1079 /// It is called when the dfs should step back on the edge.
1080 void backtrack(const Edge& edge) {}
1081 /// \brief Called when we step back from the node.
1083 /// It is called when we step back from the node.
1084 void leave(const Node& node) {}
1085 /// \brief Called when the edge examined but target of the edge
1086 /// already discovered.
1088 /// It called when the edge examined but the target of the edge
1089 /// already discovered.
1090 void examine(const Edge& edge) {}
1091 /// \brief Called for the source node of the dfs.
1093 /// It is called for the source node of the dfs.
1094 void start(const Node&) {}
1095 /// \brief Called when we leave the source node of the dfs.
1097 /// It is called when we leave the source node of the dfs.
1098 void stop(const Node&) {}
1100 template <typename _Visitor>
1101 struct Constraints {
1102 void constraints() {
1105 visitor.discover(edge);
1106 visitor.reach(node);
1107 visitor.backtrack(edge);
1108 visitor.leave(node);
1109 visitor.examine(edge);
1110 visitor.start(node);
1117 /// \brief Default traits class of DfsVisit class.
1119 /// Default traits class of DfsVisit class.
1120 /// \param _Graph Graph type.
1121 template<class _Graph>
1122 struct DfsVisitDefaultTraits {
1124 /// \brief The graph type the algorithm runs on.
1125 typedef _Graph Graph;
1127 /// \brief The type of the map that indicates which nodes are reached.
1129 /// The type of the map that indicates which nodes are reached.
1130 /// It must meet the \ref concept::WriteMap "WriteMap" concept.
1131 /// \todo named parameter to set this type, function to read and write.
1132 typedef typename Graph::template NodeMap<bool> ReachedMap;
1134 /// \brief Instantiates a ReachedMap.
1136 /// This function instantiates a \ref ReachedMap.
1137 /// \param G is the graph, to which
1138 /// we would like to define the \ref ReachedMap.
1139 static ReachedMap *createReachedMap(const Graph &graph) {
1140 return new ReachedMap(graph);
1145 /// %DFS Visit algorithm class.
1147 /// \ingroup flowalgs
1148 /// This class provides an efficient implementation of the %DFS algorithm
1149 /// with visitor interface.
1151 /// The %DfsVisit class provides an alternative interface to the Dfs
1152 /// class. It works with callback mechanism, the DfsVisit object calls
1153 /// on every dfs event the \c Visitor class member functions.
1155 /// \param _Graph The graph type the algorithm runs on. The default value is
1156 /// \ref ListGraph. The value of _Graph is not used directly by Dfs, it
1157 /// is only passed to \ref DfsDefaultTraits.
1158 /// \param _Visitor The Visitor object for the algorithm. The
1159 /// \ref DfsVisitor "DfsVisitor<_Graph>" is an empty Visitor which
1160 /// does not observe the Dfs events. If you want to observe the dfs
1161 /// events you should implement your own Visitor class.
1162 /// \param _Traits Traits class to set various data types used by the
1163 /// algorithm. The default traits class is
1164 /// \ref DfsVisitDefaultTraits "DfsVisitDefaultTraits<_Graph>".
1165 /// See \ref DfsVisitDefaultTraits for the documentation of
1166 /// a Dfs visit traits class.
1168 /// \author Jacint Szabo, Alpar Juttner and Balazs Dezso
1170 template <typename _Graph, typename _Visitor, typename _Traits>
1172 template <typename _Graph = ListGraph,
1173 typename _Visitor = DfsVisitor<_Graph>,
1174 typename _Traits = DfsDefaultTraits<_Graph> >
1179 /// \brief \ref Exception for uninitialized parameters.
1181 /// This error represents problems in the initialization
1182 /// of the parameters of the algorithms.
1183 class UninitializedParameter : public lemon::UninitializedParameter {
1185 virtual const char* exceptionName() const {
1186 return "lemon::DfsVisit::UninitializedParameter";
1190 typedef _Traits Traits;
1192 typedef typename Traits::Graph Graph;
1194 typedef _Visitor Visitor;
1196 ///The type of the map indicating which nodes are reached.
1197 typedef typename Traits::ReachedMap ReachedMap;
1201 typedef typename Graph::Node Node;
1202 typedef typename Graph::NodeIt NodeIt;
1203 typedef typename Graph::Edge Edge;
1204 typedef typename Graph::OutEdgeIt OutEdgeIt;
1206 /// Pointer to the underlying graph.
1207 const Graph *_graph;
1208 /// Pointer to the visitor object.
1210 ///Pointer to the map of reached status of the nodes.
1211 ReachedMap *_reached;
1212 ///Indicates if \ref _reached is locally allocated (\c true) or not.
1215 std::vector<typename Graph::Edge> _stack;
1218 /// \brief Creates the maps if necessary.
1220 /// Creates the maps if necessary.
1221 void create_maps() {
1223 local_reached = true;
1224 _reached = Traits::createReachedMap(*_graph);
1234 typedef DfsVisit Create;
1236 /// \name Named template parameters
1240 struct DefReachedMapTraits : public Traits {
1241 typedef T ReachedMap;
1242 static ReachedMap *createReachedMap(const Graph &graph) {
1243 throw UninitializedParameter();
1246 /// \brief \ref named-templ-param "Named parameter" for setting
1249 /// \ref named-templ-param "Named parameter" for setting ReachedMap type
1251 struct DefReachedMap : public Dfs< Graph, DefReachedMapTraits<T> > {
1252 typedef Dfs< Graph, DefReachedMapTraits<T> > Create;
1258 /// \brief Constructor.
1262 /// \param graph the graph the algorithm will run on.
1263 /// \param visitor The visitor of the algorithm.
1265 DfsVisit(const Graph& graph, Visitor& visitor)
1266 : _graph(&graph), _visitor(&visitor),
1267 _reached(0), local_reached(false) {}
1269 /// \brief Destructor.
1273 if(local_reached) delete _reached;
1276 /// \brief Sets the map indicating if a node is reached.
1278 /// Sets the map indicating if a node is reached.
1279 /// If you don't use this function before calling \ref run(),
1280 /// it will allocate one. The destuctor deallocates this
1281 /// automatically allocated map, of course.
1282 /// \return <tt> (*this) </tt>
1283 DfsVisit &reachedMap(ReachedMap &m) {
1286 local_reached=false;
1293 /// \name Execution control
1294 /// The simplest way to execute the algorithm is to use
1295 /// one of the member functions called \c run(...).
1297 /// If you need more control on the execution,
1298 /// first you must call \ref init(), then you can add several source nodes
1299 /// with \ref addSource().
1300 /// Finally \ref start() will perform the actual path
1304 /// \brief Initializes the internal data structures.
1306 /// Initializes the internal data structures.
1310 _stack.resize(countNodes(*_graph));
1312 for (NodeIt u(*_graph) ; u != INVALID ; ++u) {
1313 _reached->set(u, false);
1317 /// \brief Adds a new source node.
1319 /// Adds a new source node to the set of nodes to be processed.
1320 void addSource(Node s) {
1321 if(!(*_reached)[s]) {
1322 _reached->set(s,true);
1326 _graph->firstOut(e, s);
1328 _stack[++_stack_head] = e;
1335 /// \brief Processes the next edge.
1337 /// Processes the next edge.
1339 /// \return The processed edge.
1341 /// \pre The stack must not be empty!
1342 Edge processNextEdge() {
1343 Edge e = _stack[_stack_head];
1344 Node m = _graph->target(e);
1345 if(!(*_reached)[m]) {
1346 _visitor->discover(e);
1348 _reached->set(m, true);
1349 _graph->firstOut(_stack[++_stack_head], m);
1351 _visitor->examine(e);
1352 m = _graph->source(e);
1353 _graph->nextOut(_stack[_stack_head]);
1355 while (_stack_head>=0 && _stack[_stack_head] == INVALID) {
1358 if (_stack_head >= 0) {
1359 _visitor->backtrack(_stack[_stack_head]);
1360 m = _graph->source(_stack[_stack_head]);
1361 _graph->nextOut(_stack[_stack_head]);
1369 /// \brief Next edge to be processed.
1371 /// Next edge to be processed.
1373 /// \return The next edge to be processed or INVALID if the stack is
1376 return _stack_head >= 0 ? _stack[_stack_head] : INVALID;
1379 /// \brief Returns \c false if there are nodes
1380 /// to be processed in the queue
1382 /// Returns \c false if there are nodes
1383 /// to be processed in the queue
1385 /// \todo This should be called emptyStack() or some "neutral" name.
1386 bool emptyQueue() { return _stack_head < 0; }
1388 /// \brief Returns the number of the nodes to be processed.
1390 /// Returns the number of the nodes to be processed in the queue.
1392 ///\todo This should be called stackSize() or some "neutral" name.
1393 int queueSize() { return _stack_head + 1; }
1395 /// \brief Executes the algorithm.
1397 /// Executes the algorithm.
1399 /// \pre init() must be called and at least one node should be added
1400 /// with addSource() before using this function.
1402 while ( !emptyQueue() ) processNextEdge();
1405 /// \brief Executes the algorithm until \c dest is reached.
1407 /// Executes the algorithm until \c dest is reached.
1409 /// \pre init() must be called and at least one node should be added
1410 /// with addSource() before using this function.
1411 void start(Node dest) {
1412 while ( !emptyQueue() && _graph->target(_stack[_stack_head]) != dest)
1416 /// \brief Executes the algorithm until a condition is met.
1418 /// Executes the algorithm until a condition is met.
1420 /// \pre init() must be called and at least one node should be added
1421 /// with addSource() before using this function.
1423 /// \param nm must be a bool (or convertible) edge map. The algorithm
1424 /// will stop when it reaches an edge \c e with <tt>nm[e]==true</tt>.
1426 /// \warning Contrary to \ref Dfs and \ref Dijkstra, \c em is an edge map,
1428 template <typename EM>
1429 void start(const EM &em) {
1430 while (!emptyQueue() && !em[_stack[_stack_head]]) processNextEdge();
1433 /// \brief Runs %DFS algorithm from node \c s.
1435 /// This method runs the %DFS algorithm from a root node \c s.
1436 /// \note d.run(s) is just a shortcut of the following code.
1449 /// \name Query Functions
1450 /// The result of the %DFS algorithm can be obtained using these
1452 /// Before the use of these functions,
1453 /// either run() or start() must be called.
1455 /// \brief Checks if a node is reachable from the root.
1457 /// Returns \c true if \c v is reachable from the root(s).
1458 /// \warning The source nodes are inditated as unreachable.
1459 /// \pre Either \ref run() or \ref start()
1460 /// must be called before using this function.
1462 bool reached(Node v) { return (*_reached)[v]; }
1467 } //END OF NAMESPACE LEMON