3 * This file is a part of LEMON, a generic C++ optimization library
5 * Copyright (C) 2003-2006
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/invalid.h>
29 #include <lemon/error.h>
30 #include <lemon/maps.h>
32 #include <lemon/concept_check.h>
37 ///Default traits class of Dfs class.
39 ///Default traits class of Dfs class.
40 ///\param GR Graph type.
42 struct DfsDefaultTraits
44 ///The graph type the algorithm runs on.
46 ///\brief The type of the map that stores the last
47 ///edges of the %DFS paths.
49 ///The type of the map that stores the last
50 ///edges of the %DFS paths.
51 ///It must meet the \ref concept::WriteMap "WriteMap" concept.
53 typedef typename Graph::template NodeMap<typename GR::Edge> PredMap;
54 ///Instantiates a PredMap.
56 ///This function instantiates a \ref PredMap.
57 ///\param G is the graph, to which we would like to define the PredMap.
58 ///\todo The graph alone may be insufficient to initialize
59 static PredMap *createPredMap(const GR &G)
61 return new PredMap(G);
64 ///The type of the map that indicates which nodes are processed.
66 ///The type of the map that indicates which nodes are processed.
67 ///It must meet the \ref concept::WriteMap "WriteMap" concept.
68 ///\todo named parameter to set this type, function to read and write.
69 typedef NullMap<typename Graph::Node,bool> ProcessedMap;
70 ///Instantiates a ProcessedMap.
72 ///This function instantiates a \ref ProcessedMap.
73 ///\param g is the graph, to which
74 ///we would like to define the \ref ProcessedMap
76 static ProcessedMap *createProcessedMap(const GR &g)
78 static ProcessedMap *createProcessedMap(const GR &)
81 return new ProcessedMap();
83 ///The type of the map that indicates which nodes are reached.
85 ///The type of the map that indicates which nodes are reached.
86 ///It must meet the \ref concept::WriteMap "WriteMap" concept.
87 ///\todo named parameter to set this type, function to read and write.
88 typedef typename Graph::template NodeMap<bool> ReachedMap;
89 ///Instantiates a ReachedMap.
91 ///This function instantiates a \ref ReachedMap.
92 ///\param G is the graph, to which
93 ///we would like to define the \ref ReachedMap.
94 static ReachedMap *createReachedMap(const GR &G)
96 return new ReachedMap(G);
98 ///The type of the map that stores the dists of the nodes.
100 ///The type of the map that stores the dists of the nodes.
101 ///It must meet the \ref concept::WriteMap "WriteMap" concept.
103 typedef typename Graph::template NodeMap<int> DistMap;
104 ///Instantiates a DistMap.
106 ///This function instantiates a \ref DistMap.
107 ///\param G is the graph, to which we would like to define the \ref DistMap
108 static DistMap *createDistMap(const GR &G)
110 return new DistMap(G);
114 ///%DFS algorithm class.
117 ///This class provides an efficient implementation of the %DFS algorithm.
119 ///\param GR The graph type the algorithm runs on. The default value is
120 ///\ref ListGraph. The value of GR is not used directly by Dfs, it
121 ///is only passed to \ref DfsDefaultTraits.
122 ///\param TR Traits class to set various data types used by the algorithm.
123 ///The default traits class is
124 ///\ref DfsDefaultTraits "DfsDefaultTraits<GR>".
125 ///See \ref DfsDefaultTraits for the documentation of
126 ///a Dfs traits class.
128 ///\author Jacint Szabo and Alpar Juttner
130 template <typename GR,
133 template <typename GR=ListGraph,
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* exceptionName() const {
147 return "lemon::Dfs::UninitializedParameter";
152 ///The type of the underlying graph.
153 typedef typename TR::Graph Graph;
155 typedef typename Graph::Node Node;
157 typedef typename Graph::NodeIt NodeIt;
159 typedef typename Graph::Edge Edge;
161 typedef typename Graph::OutEdgeIt OutEdgeIt;
163 ///\brief The type of the map that stores the last
164 ///edges 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 graph.
175 ///Pointer to the map of predecessors edges.
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 Graph::OutEdgeIt> _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 Graph &G)
235 throw UninitializedParameter();
238 ///\ref named-templ-param "Named parameter" for setting PredMap type
240 ///\ref named-templ-param "Named parameter" for setting PredMap type
243 struct DefPredMap : public Dfs<Graph, DefPredMapTraits<T> > {
244 typedef Dfs<Graph, DefPredMapTraits<T> > Create;
249 struct DefDistMapTraits : public Traits {
251 static DistMap *createDistMap(const Graph &G)
253 throw UninitializedParameter();
256 ///\ref named-templ-param "Named parameter" for setting DistMap type
258 ///\ref named-templ-param "Named parameter" for setting DistMap type
262 typedef Dfs<Graph, DefDistMapTraits<T> > Create;
266 struct DefReachedMapTraits : public Traits {
267 typedef T ReachedMap;
268 static ReachedMap *createReachedMap(const Graph &G)
270 throw UninitializedParameter();
273 ///\ref named-templ-param "Named parameter" for setting ReachedMap type
275 ///\ref named-templ-param "Named parameter" for setting ReachedMap type
278 struct DefReachedMap : public Dfs< Graph, DefReachedMapTraits<T> > {
279 typedef Dfs< Graph, DefReachedMapTraits<T> > Create;
283 struct DefProcessedMapTraits : public Traits {
284 typedef T ProcessedMap;
285 static ProcessedMap *createProcessedMap(const Graph &G)
287 throw UninitializedParameter();
290 ///\ref named-templ-param "Named parameter" for setting ProcessedMap type
292 ///\ref named-templ-param "Named parameter" for setting ProcessedMap type
295 struct DefProcessedMap : public Dfs< Graph, DefProcessedMapTraits<T> > {
296 typedef Dfs< Graph, DefProcessedMapTraits<T> > Create;
299 struct DefGraphProcessedMapTraits : public Traits {
300 typedef typename Graph::template NodeMap<bool> ProcessedMap;
301 static ProcessedMap *createProcessedMap(const Graph &G)
303 return new ProcessedMap(G);
306 ///\brief \ref named-templ-param "Named parameter"
307 ///for setting the ProcessedMap type to be Graph::NodeMap<bool>.
309 ///\ref named-templ-param "Named parameter"
310 ///for setting the ProcessedMap type to be Graph::NodeMap<bool>.
311 ///If you don't set it explicitely, it will be automatically allocated.
313 class DefProcessedMapToBeDefaultMap :
314 public Dfs< Graph, DefGraphProcessedMapTraits> {
315 typedef Dfs< Graph, DefGraphProcessedMapTraits> Create;
324 ///\param _G the graph the algorithm will run on.
326 Dfs(const Graph& _G) :
328 _pred(NULL), local_pred(false),
329 _dist(NULL), local_dist(false),
330 _reached(NULL), local_reached(false),
331 _processed(NULL), local_processed(false)
337 if(local_pred) delete _pred;
338 if(local_dist) delete _dist;
339 if(local_reached) delete _reached;
340 if(local_processed) delete _processed;
343 ///Sets the map storing the predecessor edges.
345 ///Sets the map storing the predecessor edges.
346 ///If you don't use this function before calling \ref run(),
347 ///it will allocate one. The destuctor deallocates this
348 ///automatically allocated map, of course.
349 ///\return <tt> (*this) </tt>
350 Dfs &predMap(PredMap &m)
360 ///Sets the map storing the distances calculated by the algorithm.
362 ///Sets the map storing the distances calculated by the algorithm.
363 ///If you don't use this function before calling \ref run(),
364 ///it will allocate one. The destuctor deallocates this
365 ///automatically allocated map, of course.
366 ///\return <tt> (*this) </tt>
367 Dfs &distMap(DistMap &m)
377 ///Sets the map indicating if a node is reached.
379 ///Sets the map indicating if a node is reached.
380 ///If you don't use this function before calling \ref run(),
381 ///it will allocate one. The destuctor deallocates this
382 ///automatically allocated map, of course.
383 ///\return <tt> (*this) </tt>
384 Dfs &reachedMap(ReachedMap &m)
394 ///Sets the map indicating if a node is processed.
396 ///Sets the map indicating if a node is processed.
397 ///If you don't use this function before calling \ref run(),
398 ///it will allocate one. The destuctor deallocates this
399 ///automatically allocated map, of course.
400 ///\return <tt> (*this) </tt>
401 Dfs &processedMap(ProcessedMap &m)
403 if(local_processed) {
405 local_processed=false;
412 ///\name Execution control
413 ///The simplest way to execute the algorithm is to use
414 ///one of the member functions called \c run(...).
416 ///If you need more control on the execution,
417 ///first you must call \ref init(), then you can add a source node
418 ///with \ref addSource().
419 ///Finally \ref start() will perform the actual path
424 ///Initializes the internal data structures.
426 ///Initializes the internal data structures.
431 _stack.resize(countNodes(*G));
433 for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
434 _pred->set(u,INVALID);
435 // _predNode->set(u,INVALID);
436 _reached->set(u,false);
437 _processed->set(u,false);
441 ///Adds a new source node.
443 ///Adds a new source node to the set of nodes to be processed.
445 ///\warning dists are wrong (or at least strange)
446 ///in case of multiple sources.
447 void addSource(Node s)
451 _reached->set(s,true);
452 _pred->set(s,INVALID);
455 _stack[++_stack_head]=e;
456 _dist->set(s,_stack_head);
459 _processed->set(s,true);
465 ///Processes the next edge.
467 ///Processes the next edge.
469 ///\return The processed edge.
471 ///\pre The stack must not be empty!
472 Edge processNextEdge()
475 Edge e=_stack[_stack_head];
476 if(!(*_reached)[m=G->target(e)]) {
478 _reached->set(m,true);
480 _stack[_stack_head] = OutEdgeIt(*G, m);
481 _dist->set(m,_stack_head);
485 ++_stack[_stack_head];
487 while(_stack_head>=0 && _stack[_stack_head]==INVALID) {
488 _processed->set(m,true);
491 m=G->source(_stack[_stack_head]);
492 ++_stack[_stack_head];
497 ///Next edge to be processed.
499 ///Next edge to be processed.
501 ///\return The next edge to be processed or INVALID if the stack is
505 return _stack_head>=0?_stack[_stack_head]:INVALID;
508 ///\brief Returns \c false if there are nodes
509 ///to be processed in the queue
511 ///Returns \c false if there are nodes
512 ///to be processed in the queue
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.
517 int queueSize() { return _stack_head+1; }
519 ///Executes the algorithm.
521 ///Executes the algorithm.
523 ///\pre init() must be called and at least one node should be added
524 ///with addSource() before using this function.
526 ///This method runs the %DFS algorithm from the root node(s)
529 ///%DFS path to each node. The algorithm computes
531 ///- The distance of each node from the root(s) in the %DFS tree.
535 while ( !emptyQueue() ) processNextEdge();
538 ///Executes the algorithm until \c dest is reached.
540 ///Executes the algorithm until \c dest is reached.
542 ///\pre init() must be called and at least one node should be added
543 ///with addSource() before using this function.
545 ///This method runs the %DFS algorithm from the root node(s)
548 ///%DFS path to \c dest. The algorithm computes
549 ///- The %DFS path to \c dest.
550 ///- The distance of \c dest from the root(s) in the %DFS tree.
552 void start(Node dest)
554 while ( !emptyQueue() && G->target(_stack[_stack_head])!=dest )
558 ///Executes the algorithm until a condition is met.
560 ///Executes the algorithm until a condition is met.
562 ///\pre init() must be called and at least one node should be added
563 ///with addSource() before using this function.
565 ///\param em must be a bool (or convertible) edge map. The algorithm
566 ///will stop when it reaches an edge \c e with \code em[e]==true \endcode.
568 ///\warning Contrary to \ref Dfs and \ref Dijkstra, \c em is an edge map,
571 void start(const EM &em)
573 while ( !emptyQueue() && !em[_stack[_stack_head]] ) processNextEdge();
576 ///Runs %DFS algorithm from node \c s.
578 ///This method runs the %DFS algorithm from a root node \c s
581 ///%DFS path to each node. The algorithm computes
583 ///- The distance of each node from the root in the %DFS tree.
585 ///\note d.run(s) is just a shortcut of the following code.
597 ///Finds the %DFS path between \c s and \c t.
599 ///Finds the %DFS path between \c s and \c t.
601 ///\return The length of the %DFS s---t path if there exists one,
603 ///\note Apart from the return value, d.run(s,t) is
604 ///just a shortcut of the following code.
610 int run(Node s,Node t) {
614 return reached(t)?_stack_head+1:0;
619 ///\name Query Functions
620 ///The result of the %DFS algorithm can be obtained using these
622 ///Before the use of these functions,
623 ///either run() or start() must be called.
627 ///Copies the path to \c t on the DFS tree into \c p
629 ///This function copies the path to \c t on the DFS tree into \c p.
630 ///If \c t is a source itself or unreachable, then it does not
633 ///\return Returns \c true if a path to \c t was actually copied to \c p,
634 ///\c false otherwise.
637 bool getPath(P &p,Node t)
641 typename P::Builder b(p);
642 for(b.setStartNode(t);predEdge(t)!=INVALID;t=predNode(t))
643 b.pushFront(predEdge(t));
650 ///The distance of a node from the root(s).
652 ///Returns the distance of a node from the root(s).
653 ///\pre \ref run() must be called before using this function.
654 ///\warning If node \c v is unreachable from the root(s) then the return value
655 ///of this funcion is undefined.
656 int dist(Node v) const { return (*_dist)[v]; }
658 ///Returns the 'previous edge' of the %DFS tree.
660 ///For a node \c v it returns the 'previous edge'
662 ///i.e. it returns the last edge of a %DFS path from the root(s) to \c
663 ///v. It is \ref INVALID
664 ///if \c v is unreachable from the root(s) or \c v is a root. The
665 ///%DFS tree used here is equal to the %DFS tree used in
667 ///\pre Either \ref run() or \ref start() must be called before using
669 Edge predEdge(Node v) const { return (*_pred)[v];}
671 ///Returns the 'previous node' of the %DFS tree.
673 ///For a node \c v it returns the 'previous node'
675 ///i.e. it returns the last but one node from a %DFS path from the
677 ///It is INVALID if \c v is unreachable from the root(s) or
678 ///if \c v itself a root.
679 ///The %DFS tree used here is equal to the %DFS
680 ///tree used in \ref predEdge().
681 ///\pre Either \ref run() or \ref start() must be called before
682 ///using this function.
683 Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
684 G->source((*_pred)[v]); }
686 ///Returns a reference to the NodeMap of distances.
688 ///Returns a reference to the NodeMap of distances.
689 ///\pre Either \ref run() or \ref init() must
690 ///be called before using this function.
691 const DistMap &distMap() const { return *_dist;}
693 ///Returns a reference to the %DFS edge-tree map.
695 ///Returns a reference to the NodeMap of the edges of the
697 ///\pre Either \ref run() or \ref init()
698 ///must be called before using this function.
699 const PredMap &predMap() const { return *_pred;}
701 ///Checks if a node is reachable from the root.
703 ///Returns \c true if \c v is reachable from the root(s).
704 ///\warning The source nodes are inditated as unreachable.
705 ///\pre Either \ref run() or \ref start()
706 ///must be called before using this function.
708 bool reached(Node v) { return (*_reached)[v]; }
713 ///Default traits class of Dfs function.
715 ///Default traits class of Dfs function.
716 ///\param GR Graph type.
718 struct DfsWizardDefaultTraits
720 ///The graph type the algorithm runs on.
722 ///\brief The type of the map that stores the last
723 ///edges of the %DFS paths.
725 ///The type of the map that stores the last
726 ///edges of the %DFS paths.
727 ///It must meet the \ref concept::WriteMap "WriteMap" concept.
729 typedef NullMap<typename Graph::Node,typename GR::Edge> PredMap;
730 ///Instantiates a PredMap.
732 ///This function instantiates a \ref PredMap.
733 ///\param g is the graph, to which we would like to define the PredMap.
734 ///\todo The graph alone may be insufficient to initialize
736 static PredMap *createPredMap(const GR &g)
738 static PredMap *createPredMap(const GR &)
741 return new PredMap();
744 ///The type of the map that indicates which nodes are processed.
746 ///The type of the map that indicates which nodes are processed.
747 ///It must meet the \ref concept::WriteMap "WriteMap" concept.
748 ///\todo named parameter to set this type, function to read and write.
749 typedef NullMap<typename Graph::Node,bool> ProcessedMap;
750 ///Instantiates a ProcessedMap.
752 ///This function instantiates a \ref ProcessedMap.
753 ///\param g is the graph, to which
754 ///we would like to define the \ref ProcessedMap
756 static ProcessedMap *createProcessedMap(const GR &g)
758 static ProcessedMap *createProcessedMap(const GR &)
761 return new ProcessedMap();
763 ///The type of the map that indicates which nodes are reached.
765 ///The type of the map that indicates which nodes are reached.
766 ///It must meet the \ref concept::WriteMap "WriteMap" concept.
767 ///\todo named parameter to set this type, function to read and write.
768 typedef typename Graph::template NodeMap<bool> ReachedMap;
769 ///Instantiates a ReachedMap.
771 ///This function instantiates a \ref ReachedMap.
772 ///\param G is the graph, to which
773 ///we would like to define the \ref ReachedMap.
774 static ReachedMap *createReachedMap(const GR &G)
776 return new ReachedMap(G);
778 ///The type of the map that stores the dists of the nodes.
780 ///The type of the map that stores the dists of the nodes.
781 ///It must meet the \ref concept::WriteMap "WriteMap" concept.
783 typedef NullMap<typename Graph::Node,int> DistMap;
784 ///Instantiates a DistMap.
786 ///This function instantiates a \ref DistMap.
787 ///\param g is the graph, to which we would like to define the \ref DistMap
789 static DistMap *createDistMap(const GR &g)
791 static DistMap *createDistMap(const GR &)
794 return new DistMap();
798 /// Default traits used by \ref DfsWizard
800 /// To make it easier to use Dfs algorithm
801 ///we have created a wizard class.
802 /// This \ref DfsWizard class needs default traits,
803 ///as well as the \ref Dfs class.
804 /// The \ref DfsWizardBase is a class to be the default traits of the
805 /// \ref DfsWizard class.
807 class DfsWizardBase : public DfsWizardDefaultTraits<GR>
810 typedef DfsWizardDefaultTraits<GR> Base;
812 /// Type of the nodes in the graph.
813 typedef typename Base::Graph::Node Node;
815 /// Pointer to the underlying graph.
817 ///Pointer to the map of reached nodes.
819 ///Pointer to the map of processed nodes.
821 ///Pointer to the map of predecessors edges.
823 ///Pointer to the map of distances.
825 ///Pointer to the source node.
831 /// This constructor does not require parameters, therefore it initiates
832 /// all of the attributes to default values (0, INVALID).
833 DfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0),
834 _dist(0), _source(INVALID) {}
838 /// This constructor requires some parameters,
839 /// listed in the parameters list.
840 /// Others are initiated to 0.
841 /// \param g is the initial value of \ref _g
842 /// \param s is the initial value of \ref _source
843 DfsWizardBase(const GR &g, Node s=INVALID) :
844 _g((void *)&g), _reached(0), _processed(0), _pred(0),
845 _dist(0), _source(s) {}
849 /// A class to make the usage of the Dfs algorithm easier
851 /// This class is created to make it easier to use the Dfs algorithm.
852 /// It uses the functions and features of the plain \ref Dfs,
853 /// but it is much simpler to use it.
855 /// Simplicity means that the way to change the types defined
856 /// in the traits class is based on functions that returns the new class
857 /// and not on templatable built-in classes.
858 /// When using the plain \ref Dfs
859 /// the new class with the modified type comes from
860 /// the original class by using the ::
861 /// operator. In the case of \ref DfsWizard only
862 /// a function have to be called and it will
863 /// return the needed class.
865 /// It does not have own \ref run method. When its \ref run method is called
866 /// it initiates a plain \ref Dfs object, and calls the \ref Dfs::run
869 class DfsWizard : public TR
873 ///The type of the underlying graph.
874 typedef typename TR::Graph Graph;
876 typedef typename Graph::Node Node;
878 typedef typename Graph::NodeIt NodeIt;
880 typedef typename Graph::Edge Edge;
882 typedef typename Graph::OutEdgeIt OutEdgeIt;
884 ///\brief The type of the map that stores
886 typedef typename TR::ReachedMap ReachedMap;
887 ///\brief The type of the map that stores
888 ///the processed nodes
889 typedef typename TR::ProcessedMap ProcessedMap;
890 ///\brief The type of the map that stores the last
891 ///edges of the %DFS paths.
892 typedef typename TR::PredMap PredMap;
893 ///The type of the map that stores the distances of the nodes.
894 typedef typename TR::DistMap DistMap;
898 DfsWizard() : TR() {}
900 /// Constructor that requires parameters.
902 /// Constructor that requires parameters.
903 /// These parameters will be the default values for the traits class.
904 DfsWizard(const Graph &g, Node s=INVALID) :
908 DfsWizard(const TR &b) : TR(b) {}
912 ///Runs Dfs algorithm from a given node.
914 ///Runs Dfs algorithm from a given node.
915 ///The node can be given by the \ref source function.
918 if(Base::_source==INVALID) throw UninitializedParameter();
919 Dfs<Graph,TR> alg(*(Graph*)Base::_g);
920 if(Base::_reached) alg.reachedMap(*(ReachedMap*)Base::_reached);
921 if(Base::_processed) alg.processedMap(*(ProcessedMap*)Base::_processed);
922 if(Base::_pred) alg.predMap(*(PredMap*)Base::_pred);
923 if(Base::_dist) alg.distMap(*(DistMap*)Base::_dist);
924 alg.run(Base::_source);
927 ///Runs Dfs algorithm from the given node.
929 ///Runs Dfs algorithm from the given node.
930 ///\param s is the given source.
938 struct DefPredMapBase : public Base {
940 static PredMap *createPredMap(const Graph &) { return 0; };
941 DefPredMapBase(const TR &b) : TR(b) {}
944 ///\brief \ref named-templ-param "Named parameter"
945 ///function for setting PredMap type
947 /// \ref named-templ-param "Named parameter"
948 ///function for setting PredMap type
951 DfsWizard<DefPredMapBase<T> > predMap(const T &t)
953 Base::_pred=(void *)&t;
954 return DfsWizard<DefPredMapBase<T> >(*this);
959 struct DefReachedMapBase : public Base {
960 typedef T ReachedMap;
961 static ReachedMap *createReachedMap(const Graph &) { return 0; };
962 DefReachedMapBase(const TR &b) : TR(b) {}
965 ///\brief \ref named-templ-param "Named parameter"
966 ///function for setting ReachedMap
968 /// \ref named-templ-param "Named parameter"
969 ///function for setting ReachedMap
972 DfsWizard<DefReachedMapBase<T> > reachedMap(const T &t)
974 Base::_pred=(void *)&t;
975 return DfsWizard<DefReachedMapBase<T> >(*this);
980 struct DefProcessedMapBase : public Base {
981 typedef T ProcessedMap;
982 static ProcessedMap *createProcessedMap(const Graph &) { return 0; };
983 DefProcessedMapBase(const TR &b) : TR(b) {}
986 ///\brief \ref named-templ-param "Named parameter"
987 ///function for setting ProcessedMap
989 /// \ref named-templ-param "Named parameter"
990 ///function for setting ProcessedMap
993 DfsWizard<DefProcessedMapBase<T> > processedMap(const T &t)
995 Base::_pred=(void *)&t;
996 return DfsWizard<DefProcessedMapBase<T> >(*this);
1000 struct DefDistMapBase : public Base {
1002 static DistMap *createDistMap(const Graph &) { return 0; };
1003 DefDistMapBase(const TR &b) : TR(b) {}
1006 ///\brief \ref named-templ-param "Named parameter"
1007 ///function for setting DistMap type
1009 /// \ref named-templ-param "Named parameter"
1010 ///function for setting DistMap type
1013 DfsWizard<DefDistMapBase<T> > distMap(const T &t)
1015 Base::_dist=(void *)&t;
1016 return DfsWizard<DefDistMapBase<T> >(*this);
1019 /// Sets the source node, from which the Dfs algorithm runs.
1021 /// Sets the source node, from which the Dfs algorithm runs.
1022 /// \param s is the source node.
1023 DfsWizard<TR> &source(Node s)
1031 ///Function type interface for Dfs algorithm.
1033 /// \ingroup flowalgs
1034 ///Function type interface for Dfs algorithm.
1036 ///This function also has several
1037 ///\ref named-templ-func-param "named parameters",
1038 ///they are declared as the members of class \ref DfsWizard.
1040 ///example shows how to use these parameters.
1042 /// dfs(g,source).predMap(preds).run();
1044 ///\warning Don't forget to put the \ref DfsWizard::run() "run()"
1045 ///to the end of the parameter list.
1049 DfsWizard<DfsWizardBase<GR> >
1050 dfs(const GR &g,typename GR::Node s=INVALID)
1052 return DfsWizard<DfsWizardBase<GR> >(g,s);
1056 /// \brief Visitor class for dfs.
1058 /// It gives a simple interface for a functional interface for dfs
1059 /// traversal. The traversal on a linear data structure.
1060 template <typename _Graph>
1062 typedef _Graph Graph;
1063 typedef typename Graph::Edge Edge;
1064 typedef typename Graph::Node Node;
1065 /// \brief Called when the edge reach a node.
1067 /// It is called when the dfs find an edge which target is not
1069 void discover(const Edge& edge) {}
1070 /// \brief Called when the node reached first time.
1072 /// It is Called when the node reached first time.
1073 void reach(const Node& node) {}
1074 /// \brief Called when we step back on an edge.
1076 /// It is called when the dfs should step back on the edge.
1077 void backtrack(const Edge& edge) {}
1078 /// \brief Called when we step back from the node.
1080 /// It is called when we step back from the node.
1081 void leave(const Node& node) {}
1082 /// \brief Called when the edge examined but target of the edge
1083 /// already discovered.
1085 /// It called when the edge examined but the target of the edge
1086 /// already discovered.
1087 void examine(const Edge& edge) {}
1088 /// \brief Called for the source node of the dfs.
1090 /// It is called for the source node of the dfs.
1091 void start(const Node& node) {}
1092 /// \brief Called when we leave the source node of the dfs.
1094 /// It is called when we leave the source node of the dfs.
1095 void stop(const Node& node) {}
1099 template <typename _Graph>
1101 typedef _Graph Graph;
1102 typedef typename Graph::Edge Edge;
1103 typedef typename Graph::Node Node;
1104 void discover(const Edge&) {}
1105 void reach(const Node&) {}
1106 void backtrack(const Edge&) {}
1107 void leave(const Node&) {}
1108 void examine(const Edge&) {}
1109 void start(const Node&) {}
1110 void stop(const Node&) {}
1112 template <typename _Visitor>
1113 struct Constraints {
1114 void constraints() {
1117 visitor.discover(edge);
1118 visitor.reach(node);
1119 visitor.backtrack(edge);
1120 visitor.leave(node);
1121 visitor.examine(edge);
1122 visitor.start(node);
1130 /// \brief Default traits class of DfsVisit class.
1132 /// Default traits class of DfsVisit class.
1133 /// \param _Graph Graph type.
1134 template<class _Graph>
1135 struct DfsVisitDefaultTraits {
1137 /// \brief The graph type the algorithm runs on.
1138 typedef _Graph Graph;
1140 /// \brief The type of the map that indicates which nodes are reached.
1142 /// The type of the map that indicates which nodes are reached.
1143 /// It must meet the \ref concept::WriteMap "WriteMap" concept.
1144 /// \todo named parameter to set this type, function to read and write.
1145 typedef typename Graph::template NodeMap<bool> ReachedMap;
1147 /// \brief Instantiates a ReachedMap.
1149 /// This function instantiates a \ref ReachedMap.
1150 /// \param graph is the graph, to which
1151 /// we would like to define the \ref ReachedMap.
1152 static ReachedMap *createReachedMap(const Graph &graph) {
1153 return new ReachedMap(graph);
1158 /// %DFS Visit algorithm class.
1160 /// \ingroup flowalgs
1161 /// This class provides an efficient implementation of the %DFS algorithm
1162 /// with visitor interface.
1164 /// The %DfsVisit class provides an alternative interface to the Dfs
1165 /// class. It works with callback mechanism, the DfsVisit object calls
1166 /// on every dfs event the \c Visitor class member functions.
1168 /// \param _Graph The graph type the algorithm runs on. The default value is
1169 /// \ref ListGraph. The value of _Graph is not used directly by Dfs, it
1170 /// is only passed to \ref DfsDefaultTraits.
1171 /// \param _Visitor The Visitor object for the algorithm. The
1172 /// \ref DfsVisitor "DfsVisitor<_Graph>" is an empty Visitor which
1173 /// does not observe the Dfs events. If you want to observe the dfs
1174 /// events you should implement your own Visitor class.
1175 /// \param _Traits Traits class to set various data types used by the
1176 /// algorithm. The default traits class is
1177 /// \ref DfsVisitDefaultTraits "DfsVisitDefaultTraits<_Graph>".
1178 /// See \ref DfsVisitDefaultTraits for the documentation of
1179 /// a Dfs visit traits class.
1181 /// \author Jacint Szabo, Alpar Juttner and Balazs Dezso
1183 template <typename _Graph, typename _Visitor, typename _Traits>
1185 template <typename _Graph = ListGraph,
1186 typename _Visitor = DfsVisitor<_Graph>,
1187 typename _Traits = DfsDefaultTraits<_Graph> >
1192 /// \brief \ref Exception for uninitialized parameters.
1194 /// This error represents problems in the initialization
1195 /// of the parameters of the algorithms.
1196 class UninitializedParameter : public lemon::UninitializedParameter {
1198 virtual const char* exceptionName() const {
1199 return "lemon::DfsVisit::UninitializedParameter";
1203 typedef _Traits Traits;
1205 typedef typename Traits::Graph Graph;
1207 typedef _Visitor Visitor;
1209 ///The type of the map indicating which nodes are reached.
1210 typedef typename Traits::ReachedMap ReachedMap;
1214 typedef typename Graph::Node Node;
1215 typedef typename Graph::NodeIt NodeIt;
1216 typedef typename Graph::Edge Edge;
1217 typedef typename Graph::OutEdgeIt OutEdgeIt;
1219 /// Pointer to the underlying graph.
1220 const Graph *_graph;
1221 /// Pointer to the visitor object.
1223 ///Pointer to the map of reached status of the nodes.
1224 ReachedMap *_reached;
1225 ///Indicates if \ref _reached is locally allocated (\c true) or not.
1228 std::vector<typename Graph::Edge> _stack;
1231 /// \brief Creates the maps if necessary.
1233 /// Creates the maps if necessary.
1234 void create_maps() {
1236 local_reached = true;
1237 _reached = Traits::createReachedMap(*_graph);
1247 typedef DfsVisit Create;
1249 /// \name Named template parameters
1253 struct DefReachedMapTraits : public Traits {
1254 typedef T ReachedMap;
1255 static ReachedMap *createReachedMap(const Graph &graph) {
1256 throw UninitializedParameter();
1259 /// \brief \ref named-templ-param "Named parameter" for setting
1262 /// \ref named-templ-param "Named parameter" for setting ReachedMap type
1264 struct DefReachedMap : public DfsVisit< Graph, Visitor,
1265 DefReachedMapTraits<T> > {
1266 typedef DfsVisit< Graph, Visitor, DefReachedMapTraits<T> > Create;
1272 /// \brief Constructor.
1276 /// \param graph the graph the algorithm will run on.
1277 /// \param visitor The visitor of the algorithm.
1279 DfsVisit(const Graph& graph, Visitor& visitor)
1280 : _graph(&graph), _visitor(&visitor),
1281 _reached(0), local_reached(false) {}
1283 /// \brief Destructor.
1287 if(local_reached) delete _reached;
1290 /// \brief Sets the map indicating if a node is reached.
1292 /// Sets the map indicating if a node is reached.
1293 /// If you don't use this function before calling \ref run(),
1294 /// it will allocate one. The destuctor deallocates this
1295 /// automatically allocated map, of course.
1296 /// \return <tt> (*this) </tt>
1297 DfsVisit &reachedMap(ReachedMap &m) {
1300 local_reached=false;
1307 /// \name Execution control
1308 /// The simplest way to execute the algorithm is to use
1309 /// one of the member functions called \c run(...).
1311 /// If you need more control on the execution,
1312 /// first you must call \ref init(), then you can adda source node
1313 /// with \ref addSource().
1314 /// Finally \ref start() will perform the actual path
1318 /// \brief Initializes the internal data structures.
1320 /// Initializes the internal data structures.
1324 _stack.resize(countNodes(*_graph));
1326 for (NodeIt u(*_graph) ; u != INVALID ; ++u) {
1327 _reached->set(u, false);
1331 /// \brief Adds a new source node.
1333 /// Adds a new source node to the set of nodes to be processed.
1334 void addSource(Node s) {
1335 if(!(*_reached)[s]) {
1336 _reached->set(s,true);
1340 _graph->firstOut(e, s);
1342 _stack[++_stack_head] = e;
1349 /// \brief Processes the next edge.
1351 /// Processes the next edge.
1353 /// \return The processed edge.
1355 /// \pre The stack must not be empty!
1356 Edge processNextEdge() {
1357 Edge e = _stack[_stack_head];
1358 Node m = _graph->target(e);
1359 if(!(*_reached)[m]) {
1360 _visitor->discover(e);
1362 _reached->set(m, true);
1363 _graph->firstOut(_stack[++_stack_head], m);
1365 _visitor->examine(e);
1366 m = _graph->source(e);
1367 _graph->nextOut(_stack[_stack_head]);
1369 while (_stack_head>=0 && _stack[_stack_head] == INVALID) {
1372 if (_stack_head >= 0) {
1373 _visitor->backtrack(_stack[_stack_head]);
1374 m = _graph->source(_stack[_stack_head]);
1375 _graph->nextOut(_stack[_stack_head]);
1383 /// \brief Next edge to be processed.
1385 /// Next edge to be processed.
1387 /// \return The next edge to be processed or INVALID if the stack is
1390 return _stack_head >= 0 ? _stack[_stack_head] : INVALID;
1393 /// \brief Returns \c false if there are nodes
1394 /// to be processed in the queue
1396 /// Returns \c false if there are nodes
1397 /// to be processed in the queue
1398 bool emptyQueue() { return _stack_head < 0; }
1400 /// \brief Returns the number of the nodes to be processed.
1402 /// Returns the number of the nodes to be processed in the queue.
1403 int queueSize() { return _stack_head + 1; }
1405 /// \brief Executes the algorithm.
1407 /// Executes the algorithm.
1409 /// \pre init() must be called and at least one node should be added
1410 /// with addSource() before using this function.
1412 while ( !emptyQueue() ) processNextEdge();
1415 /// \brief Executes the algorithm until \c dest is reached.
1417 /// Executes the algorithm until \c dest is reached.
1419 /// \pre init() must be called and at least one node should be added
1420 /// with addSource() before using this function.
1421 void start(Node dest) {
1422 while ( !emptyQueue() && _graph->target(_stack[_stack_head]) != dest)
1426 /// \brief Executes the algorithm until a condition is met.
1428 /// Executes the algorithm until a condition is met.
1430 /// \pre init() must be called and at least one node should be added
1431 /// with addSource() before using this function.
1433 /// \param em must be a bool (or convertible) edge map. The algorithm
1434 /// will stop when it reaches an edge \c e with \code nm[e]==true \endcode.
1436 /// \warning Contrary to \ref Dfs and \ref Dijkstra, \c em is an edge map,
1438 template <typename EM>
1439 void start(const EM &em) {
1440 while (!emptyQueue() && !em[_stack[_stack_head]]) processNextEdge();
1443 /// \brief Runs %DFS algorithm from node \c s.
1445 /// This method runs the %DFS algorithm from a root node \c s.
1446 /// \note d.run(s) is just a shortcut of the following code.
1459 /// \name Query Functions
1460 /// The result of the %DFS algorithm can be obtained using these
1462 /// Before the use of these functions,
1463 /// either run() or start() must be called.
1465 /// \brief Checks if a node is reachable from the root.
1467 /// Returns \c true if \c v is reachable from the root(s).
1468 /// \warning The source nodes are inditated as unreachable.
1469 /// \pre Either \ref run() or \ref start()
1470 /// must be called before using this function.
1472 bool reached(Node v) { return (*_reached)[v]; }
1477 } //END OF NAMESPACE LEMON