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/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 ///\param GR Graph type.
43 struct DfsDefaultTraits
45 ///The graph type the algorithm runs on.
47 ///\brief The type of the map that stores the last
48 ///edges of the %DFS paths.
50 ///The type of the map that stores the last
51 ///edges of the %DFS paths.
52 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
54 typedef typename Graph::template NodeMap<typename GR::Edge> PredMap;
55 ///Instantiates a PredMap.
57 ///This function instantiates a \ref PredMap.
58 ///\param G is the graph, to which we would like to define the PredMap.
59 ///\todo The graph 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 Graph::Node,bool> ProcessedMap;
71 ///Instantiates a ProcessedMap.
73 ///This function instantiates a \ref ProcessedMap.
74 ///\param g is the graph, 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 Graph::template NodeMap<bool> ReachedMap;
90 ///Instantiates a ReachedMap.
92 ///This function instantiates a \ref ReachedMap.
93 ///\param G is the graph, 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 Graph::template NodeMap<int> DistMap;
105 ///Instantiates a DistMap.
107 ///This function instantiates a \ref DistMap.
108 ///\param G is the graph, to which we would like to define the \ref DistMap
109 static DistMap *createDistMap(const GR &G)
111 return new DistMap(G);
115 ///%DFS algorithm class.
118 ///This class provides an efficient implementation of the %DFS algorithm.
120 ///\param GR The graph type the algorithm runs on. The default value is
121 ///\ref ListGraph. The value of GR is not used directly by Dfs, it
122 ///is only passed to \ref DfsDefaultTraits.
123 ///\param TR Traits class to set various data types used by the algorithm.
124 ///The default traits class is
125 ///\ref DfsDefaultTraits "DfsDefaultTraits<GR>".
126 ///See \ref DfsDefaultTraits for the documentation of
127 ///a Dfs traits class.
129 ///\author Jacint Szabo and Alpar Juttner
131 template <typename GR,
134 template <typename GR=ListGraph,
135 typename TR=DfsDefaultTraits<GR> >
140 * \brief \ref Exception for uninitialized parameters.
142 * This error represents problems in the initialization
143 * of the parameters of the algorithms.
145 class UninitializedParameter : public lemon::UninitializedParameter {
147 virtual const char* what() const throw() {
148 return "lemon::Dfs::UninitializedParameter";
153 ///The type of the underlying graph.
154 typedef typename TR::Graph Graph;
156 typedef typename Graph::Node Node;
158 typedef typename Graph::NodeIt NodeIt;
160 typedef typename Graph::Edge Edge;
162 typedef typename Graph::OutEdgeIt OutEdgeIt;
164 ///\brief The type of the map that stores the last
165 ///edges of the %DFS paths.
166 typedef typename TR::PredMap PredMap;
167 ///The type of the map indicating which nodes are reached.
168 typedef typename TR::ReachedMap ReachedMap;
169 ///The type of the map indicating which nodes are processed.
170 typedef typename TR::ProcessedMap ProcessedMap;
171 ///The type of the map that stores the dists of the nodes.
172 typedef typename TR::DistMap DistMap;
174 /// Pointer to the underlying graph.
176 ///Pointer to the map of predecessors edges.
178 ///Indicates if \ref _pred is locally allocated (\c true) or not.
180 ///Pointer to the map of distances.
182 ///Indicates if \ref _dist is locally allocated (\c true) or not.
184 ///Pointer to the map of reached status of the nodes.
185 ReachedMap *_reached;
186 ///Indicates if \ref _reached is locally allocated (\c true) or not.
188 ///Pointer to the map of processed status of the nodes.
189 ProcessedMap *_processed;
190 ///Indicates if \ref _processed is locally allocated (\c true) or not.
191 bool local_processed;
193 std::vector<typename Graph::OutEdgeIt> _stack;
196 ///Creates the maps if necessary.
198 ///\todo Better memory allocation (instead of new).
203 _pred = Traits::createPredMap(*G);
207 _dist = Traits::createDistMap(*G);
210 local_reached = true;
211 _reached = Traits::createReachedMap(*G);
214 local_processed = true;
215 _processed = Traits::createProcessedMap(*G);
227 ///\name Named template parameters
232 struct DefPredMapTraits : public Traits {
234 static PredMap *createPredMap(const Graph &G)
236 throw UninitializedParameter();
239 ///\ref named-templ-param "Named parameter" for setting PredMap type
241 ///\ref named-templ-param "Named parameter" for setting PredMap type
244 struct DefPredMap : public Dfs<Graph, DefPredMapTraits<T> > {
245 typedef Dfs<Graph, DefPredMapTraits<T> > Create;
250 struct DefDistMapTraits : public Traits {
252 static DistMap *createDistMap(const Graph &)
254 throw UninitializedParameter();
257 ///\ref named-templ-param "Named parameter" for setting DistMap type
259 ///\ref named-templ-param "Named parameter" for setting DistMap type
263 typedef Dfs<Graph, DefDistMapTraits<T> > Create;
267 struct DefReachedMapTraits : public Traits {
268 typedef T ReachedMap;
269 static ReachedMap *createReachedMap(const Graph &)
271 throw UninitializedParameter();
274 ///\ref named-templ-param "Named parameter" for setting ReachedMap type
276 ///\ref named-templ-param "Named parameter" for setting ReachedMap type
279 struct DefReachedMap : public Dfs< Graph, DefReachedMapTraits<T> > {
280 typedef Dfs< Graph, DefReachedMapTraits<T> > Create;
284 struct DefProcessedMapTraits : public Traits {
285 typedef T ProcessedMap;
286 static ProcessedMap *createProcessedMap(const Graph &)
288 throw UninitializedParameter();
291 ///\ref named-templ-param "Named parameter" for setting ProcessedMap type
293 ///\ref named-templ-param "Named parameter" for setting ProcessedMap type
296 struct DefProcessedMap : public Dfs< Graph, DefProcessedMapTraits<T> > {
297 typedef Dfs< Graph, DefProcessedMapTraits<T> > Create;
300 struct DefGraphProcessedMapTraits : public Traits {
301 typedef typename Graph::template NodeMap<bool> ProcessedMap;
302 static ProcessedMap *createProcessedMap(const Graph &G)
304 return new ProcessedMap(G);
307 ///\brief \ref named-templ-param "Named parameter"
308 ///for setting the ProcessedMap type to be Graph::NodeMap<bool>.
310 ///\ref named-templ-param "Named parameter"
311 ///for setting the ProcessedMap type to be Graph::NodeMap<bool>.
312 ///If you don't set it explicitely, it will be automatically allocated.
314 class DefProcessedMapToBeDefaultMap :
315 public Dfs< Graph, DefGraphProcessedMapTraits> {
316 typedef Dfs< Graph, DefGraphProcessedMapTraits> Create;
325 ///\param _G the graph the algorithm will run on.
327 Dfs(const Graph& _G) :
329 _pred(NULL), local_pred(false),
330 _dist(NULL), local_dist(false),
331 _reached(NULL), local_reached(false),
332 _processed(NULL), local_processed(false)
338 if(local_pred) delete _pred;
339 if(local_dist) delete _dist;
340 if(local_reached) delete _reached;
341 if(local_processed) delete _processed;
344 ///Sets the map storing the predecessor edges.
346 ///Sets the map storing the predecessor edges.
347 ///If you don't use this function before calling \ref run(),
348 ///it will allocate one. The destuctor deallocates this
349 ///automatically allocated map, of course.
350 ///\return <tt> (*this) </tt>
351 Dfs &predMap(PredMap &m)
361 ///Sets the map storing the distances calculated by the algorithm.
363 ///Sets the map storing the distances calculated by the algorithm.
364 ///If you don't use this function before calling \ref run(),
365 ///it will allocate one. The destuctor deallocates this
366 ///automatically allocated map, of course.
367 ///\return <tt> (*this) </tt>
368 Dfs &distMap(DistMap &m)
378 ///Sets the map indicating if a node is reached.
380 ///Sets the map indicating if a node is reached.
381 ///If you don't use this function before calling \ref run(),
382 ///it will allocate one. The destuctor deallocates this
383 ///automatically allocated map, of course.
384 ///\return <tt> (*this) </tt>
385 Dfs &reachedMap(ReachedMap &m)
395 ///Sets the map indicating if a node is processed.
397 ///Sets the map indicating if a node is processed.
398 ///If you don't use this function before calling \ref run(),
399 ///it will allocate one. The destuctor deallocates this
400 ///automatically allocated map, of course.
401 ///\return <tt> (*this) </tt>
402 Dfs &processedMap(ProcessedMap &m)
404 if(local_processed) {
406 local_processed=false;
413 ///\name Execution control
414 ///The simplest way to execute the algorithm is to use
415 ///one of the member functions called \c run(...).
417 ///If you need more control on the execution,
418 ///first you must call \ref init(), then you can add a source node
419 ///with \ref addSource().
420 ///Finally \ref start() will perform the actual path
425 ///Initializes the internal data structures.
427 ///Initializes the internal data structures.
432 _stack.resize(countNodes(*G));
434 for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
435 _pred->set(u,INVALID);
436 // _predNode->set(u,INVALID);
437 _reached->set(u,false);
438 _processed->set(u,false);
442 ///Adds a new source node.
444 ///Adds a new source node to the set of nodes to be processed.
446 ///\warning dists are wrong (or at least strange)
447 ///in case of multiple sources.
448 void addSource(Node s)
452 _reached->set(s,true);
453 _pred->set(s,INVALID);
456 _stack[++_stack_head]=e;
457 _dist->set(s,_stack_head);
460 _processed->set(s,true);
466 ///Processes the next edge.
468 ///Processes the next edge.
470 ///\return The processed edge.
472 ///\pre The stack must not be empty!
473 Edge processNextEdge()
476 Edge e=_stack[_stack_head];
477 if(!(*_reached)[m=G->target(e)]) {
479 _reached->set(m,true);
481 _stack[_stack_head] = OutEdgeIt(*G, m);
482 _dist->set(m,_stack_head);
486 ++_stack[_stack_head];
488 while(_stack_head>=0 && _stack[_stack_head]==INVALID) {
489 _processed->set(m,true);
492 m=G->source(_stack[_stack_head]);
493 ++_stack[_stack_head];
498 ///Next edge to be processed.
500 ///Next edge to be processed.
502 ///\return The next edge to be processed or INVALID if the stack is
506 return _stack_head>=0?_stack[_stack_head]:INVALID;
509 ///\brief Returns \c false if there are nodes
510 ///to be processed in the queue
512 ///Returns \c false if there are nodes
513 ///to be processed in the queue
514 bool emptyQueue() { return _stack_head<0; }
515 ///Returns the number of the nodes to be processed.
517 ///Returns the number of the nodes to be processed in the queue.
518 int queueSize() { return _stack_head+1; }
520 ///Executes the algorithm.
522 ///Executes the algorithm.
524 ///\pre init() must be called and at least one node should be added
525 ///with addSource() before using this function.
527 ///This method runs the %DFS algorithm from the root node(s)
530 ///%DFS path to each node. The algorithm computes
532 ///- The distance of each node from the root(s) in the %DFS tree.
536 while ( !emptyQueue() ) processNextEdge();
539 ///Executes the algorithm until \c dest is reached.
541 ///Executes the algorithm until \c dest is reached.
543 ///\pre init() must be called and at least one node should be added
544 ///with addSource() before using this function.
546 ///This method runs the %DFS algorithm from the root node(s)
549 ///%DFS path to \c dest. The algorithm computes
550 ///- The %DFS path to \c dest.
551 ///- The distance of \c dest from the root(s) in the %DFS tree.
553 void start(Node dest)
555 while ( !emptyQueue() && G->target(_stack[_stack_head])!=dest )
559 ///Executes the algorithm until a condition is met.
561 ///Executes the algorithm until a condition is met.
563 ///\pre init() must be called and at least one node should be added
564 ///with addSource() before using this function.
566 ///\param em must be a bool (or convertible) edge map. The algorithm
567 ///will stop when it reaches an edge \c e with \code em[e]==true \endcode.
569 ///\warning Contrary to \ref Dfs and \ref Dijkstra, \c em is an edge map,
572 void start(const EM &em)
574 while ( !emptyQueue() && !em[_stack[_stack_head]] ) processNextEdge();
577 ///Runs %DFS algorithm to visit all nodes in the graph.
579 ///This method runs the %DFS algorithm in order to
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() is just a shortcut of the following code.
588 /// for (NodeIt it(graph); it != INVALID; ++it) {
589 /// if (!d.reached(it)) {
597 for (NodeIt it(*G); it != INVALID; ++it) {
605 ///Runs %DFS algorithm from node \c s.
607 ///This method runs the %DFS algorithm from a root node \c s
610 ///%DFS path to each node. The algorithm computes
612 ///- The distance of each node from the root in the %DFS tree.
614 ///\note d.run(s) is just a shortcut of the following code.
626 ///Finds the %DFS path between \c s and \c t.
628 ///Finds the %DFS path between \c s and \c t.
630 ///\return The length of the %DFS s---t path if there exists one,
632 ///\note Apart from the return value, d.run(s,t) is
633 ///just a shortcut of the following code.
639 int run(Node s,Node t) {
643 return reached(t)?_stack_head+1:0;
648 ///\name Query Functions
649 ///The result of the %DFS algorithm can be obtained using these
651 ///Before the use of these functions,
652 ///either run() or start() must be called.
656 typedef PredMapPath<Graph, PredMap> Path;
658 ///Gives back the shortest path.
660 ///Gives back the shortest path.
661 ///\pre The \c t should be reachable from the source.
664 return Path(*G, *_pred, t);
667 ///The distance of a node from the root(s).
669 ///Returns the distance of a node from the root(s).
670 ///\pre \ref run() must be called before using this function.
671 ///\warning If node \c v is unreachable from the root(s) then the return
672 ///value of this funcion is undefined.
673 int dist(Node v) const { return (*_dist)[v]; }
675 ///Returns the 'previous edge' of the %DFS tree.
677 ///For a node \c v it returns the 'previous edge'
679 ///i.e. it returns the last edge of a %DFS path from the root(s) to \c
680 ///v. It is \ref INVALID
681 ///if \c v is unreachable from the root(s) or \c v is a root. The
682 ///%DFS tree used here is equal to the %DFS tree used in
684 ///\pre Either \ref run() or \ref start() must be called before using
686 Edge predEdge(Node v) const { return (*_pred)[v];}
688 ///Returns the 'previous node' of the %DFS tree.
690 ///For a node \c v it returns the 'previous node'
692 ///i.e. it returns the last but one node from a %DFS path from the
694 ///It is INVALID if \c v is unreachable from the root(s) or
695 ///if \c v itself a root.
696 ///The %DFS tree used here is equal to the %DFS
697 ///tree used in \ref predEdge().
698 ///\pre Either \ref run() or \ref start() must be called before
699 ///using this function.
700 Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
701 G->source((*_pred)[v]); }
703 ///Returns a reference to the NodeMap of distances.
705 ///Returns a reference to the NodeMap of distances.
706 ///\pre Either \ref run() or \ref init() must
707 ///be called before using this function.
708 const DistMap &distMap() const { return *_dist;}
710 ///Returns a reference to the %DFS edge-tree map.
712 ///Returns a reference to the NodeMap of the edges of the
714 ///\pre Either \ref run() or \ref init()
715 ///must be called before using this function.
716 const PredMap &predMap() const { return *_pred;}
718 ///Checks if a node is reachable from the root.
720 ///Returns \c true if \c v is reachable from the root(s).
721 ///\warning The source nodes are inditated as unreachable.
722 ///\pre Either \ref run() or \ref start()
723 ///must be called before using this function.
725 bool reached(Node v) { return (*_reached)[v]; }
730 ///Default traits class of Dfs function.
732 ///Default traits class of Dfs function.
733 ///\param GR Graph type.
735 struct DfsWizardDefaultTraits
737 ///The graph type the algorithm runs on.
739 ///\brief The type of the map that stores the last
740 ///edges of the %DFS paths.
742 ///The type of the map that stores the last
743 ///edges of the %DFS paths.
744 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
746 typedef NullMap<typename Graph::Node,typename GR::Edge> PredMap;
747 ///Instantiates a PredMap.
749 ///This function instantiates a \ref PredMap.
750 ///\param g is the graph, to which we would like to define the PredMap.
751 ///\todo The graph alone may be insufficient to initialize
753 static PredMap *createPredMap(const GR &g)
755 static PredMap *createPredMap(const GR &)
758 return new PredMap();
761 ///The type of the map that indicates which nodes are processed.
763 ///The type of the map that indicates which nodes are processed.
764 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
765 ///\todo named parameter to set this type, function to read and write.
766 typedef NullMap<typename Graph::Node,bool> ProcessedMap;
767 ///Instantiates a ProcessedMap.
769 ///This function instantiates a \ref ProcessedMap.
770 ///\param g is the graph, to which
771 ///we would like to define the \ref ProcessedMap
773 static ProcessedMap *createProcessedMap(const GR &g)
775 static ProcessedMap *createProcessedMap(const GR &)
778 return new ProcessedMap();
780 ///The type of the map that indicates which nodes are reached.
782 ///The type of the map that indicates which nodes are reached.
783 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
784 ///\todo named parameter to set this type, function to read and write.
785 typedef typename Graph::template NodeMap<bool> ReachedMap;
786 ///Instantiates a ReachedMap.
788 ///This function instantiates a \ref ReachedMap.
789 ///\param G is the graph, to which
790 ///we would like to define the \ref ReachedMap.
791 static ReachedMap *createReachedMap(const GR &G)
793 return new ReachedMap(G);
795 ///The type of the map that stores the dists of the nodes.
797 ///The type of the map that stores the dists of the nodes.
798 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
800 typedef NullMap<typename Graph::Node,int> DistMap;
801 ///Instantiates a DistMap.
803 ///This function instantiates a \ref DistMap.
804 ///\param g is the graph, to which we would like to define the \ref DistMap
806 static DistMap *createDistMap(const GR &g)
808 static DistMap *createDistMap(const GR &)
811 return new DistMap();
815 /// Default traits used by \ref DfsWizard
817 /// To make it easier to use Dfs algorithm
818 ///we have created a wizard class.
819 /// This \ref DfsWizard class needs default traits,
820 ///as well as the \ref Dfs class.
821 /// The \ref DfsWizardBase is a class to be the default traits of the
822 /// \ref DfsWizard class.
824 class DfsWizardBase : public DfsWizardDefaultTraits<GR>
827 typedef DfsWizardDefaultTraits<GR> Base;
829 /// Type of the nodes in the graph.
830 typedef typename Base::Graph::Node Node;
832 /// Pointer to the underlying graph.
834 ///Pointer to the map of reached nodes.
836 ///Pointer to the map of processed nodes.
838 ///Pointer to the map of predecessors edges.
840 ///Pointer to the map of distances.
842 ///Pointer to the source node.
848 /// This constructor does not require parameters, therefore it initiates
849 /// all of the attributes to default values (0, INVALID).
850 DfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0),
851 _dist(0), _source(INVALID) {}
855 /// This constructor requires some parameters,
856 /// listed in the parameters list.
857 /// Others are initiated to 0.
858 /// \param g is the initial value of \ref _g
859 /// \param s is the initial value of \ref _source
860 DfsWizardBase(const GR &g, Node s=INVALID) :
861 _g((void *)&g), _reached(0), _processed(0), _pred(0),
862 _dist(0), _source(s) {}
866 /// A class to make the usage of the Dfs algorithm easier
868 /// This class is created to make it easier to use the Dfs algorithm.
869 /// It uses the functions and features of the plain \ref Dfs,
870 /// but it is much simpler to use it.
872 /// Simplicity means that the way to change the types defined
873 /// in the traits class is based on functions that returns the new class
874 /// and not on templatable built-in classes.
875 /// When using the plain \ref Dfs
876 /// the new class with the modified type comes from
877 /// the original class by using the ::
878 /// operator. In the case of \ref DfsWizard only
879 /// a function have to be called and it will
880 /// return the needed class.
882 /// It does not have own \ref run method. When its \ref run method is called
883 /// it initiates a plain \ref Dfs object, and calls the \ref Dfs::run
886 class DfsWizard : public TR
890 ///The type of the underlying graph.
891 typedef typename TR::Graph Graph;
893 typedef typename Graph::Node Node;
895 typedef typename Graph::NodeIt NodeIt;
897 typedef typename Graph::Edge Edge;
899 typedef typename Graph::OutEdgeIt OutEdgeIt;
901 ///\brief The type of the map that stores
903 typedef typename TR::ReachedMap ReachedMap;
904 ///\brief The type of the map that stores
905 ///the processed nodes
906 typedef typename TR::ProcessedMap ProcessedMap;
907 ///\brief The type of the map that stores the last
908 ///edges of the %DFS paths.
909 typedef typename TR::PredMap PredMap;
910 ///The type of the map that stores the distances of the nodes.
911 typedef typename TR::DistMap DistMap;
915 DfsWizard() : TR() {}
917 /// Constructor that requires parameters.
919 /// Constructor that requires parameters.
920 /// These parameters will be the default values for the traits class.
921 DfsWizard(const Graph &g, Node s=INVALID) :
925 DfsWizard(const TR &b) : TR(b) {}
929 ///Runs Dfs algorithm from a given node.
931 ///Runs Dfs algorithm from a given node.
932 ///The node can be given by the \ref source function.
935 if(Base::_source==INVALID) throw UninitializedParameter();
936 Dfs<Graph,TR> alg(*(Graph*)Base::_g);
937 if(Base::_reached) alg.reachedMap(*(ReachedMap*)Base::_reached);
938 if(Base::_processed) alg.processedMap(*(ProcessedMap*)Base::_processed);
939 if(Base::_pred) alg.predMap(*(PredMap*)Base::_pred);
940 if(Base::_dist) alg.distMap(*(DistMap*)Base::_dist);
941 alg.run(Base::_source);
944 ///Runs Dfs algorithm from the given node.
946 ///Runs Dfs algorithm from the given node.
947 ///\param s is the given source.
955 struct DefPredMapBase : public Base {
957 static PredMap *createPredMap(const Graph &) { return 0; };
958 DefPredMapBase(const TR &b) : TR(b) {}
961 ///\brief \ref named-templ-param "Named parameter"
962 ///function for setting PredMap type
964 /// \ref named-templ-param "Named parameter"
965 ///function for setting PredMap type
968 DfsWizard<DefPredMapBase<T> > predMap(const T &t)
970 Base::_pred=(void *)&t;
971 return DfsWizard<DefPredMapBase<T> >(*this);
976 struct DefReachedMapBase : public Base {
977 typedef T ReachedMap;
978 static ReachedMap *createReachedMap(const Graph &) { return 0; };
979 DefReachedMapBase(const TR &b) : TR(b) {}
982 ///\brief \ref named-templ-param "Named parameter"
983 ///function for setting ReachedMap
985 /// \ref named-templ-param "Named parameter"
986 ///function for setting ReachedMap
989 DfsWizard<DefReachedMapBase<T> > reachedMap(const T &t)
991 Base::_pred=(void *)&t;
992 return DfsWizard<DefReachedMapBase<T> >(*this);
997 struct DefProcessedMapBase : public Base {
998 typedef T ProcessedMap;
999 static ProcessedMap *createProcessedMap(const Graph &) { return 0; };
1000 DefProcessedMapBase(const TR &b) : TR(b) {}
1003 ///\brief \ref named-templ-param "Named parameter"
1004 ///function for setting ProcessedMap
1006 /// \ref named-templ-param "Named parameter"
1007 ///function for setting ProcessedMap
1010 DfsWizard<DefProcessedMapBase<T> > processedMap(const T &t)
1012 Base::_pred=(void *)&t;
1013 return DfsWizard<DefProcessedMapBase<T> >(*this);
1017 struct DefDistMapBase : public Base {
1019 static DistMap *createDistMap(const Graph &) { return 0; };
1020 DefDistMapBase(const TR &b) : TR(b) {}
1023 ///\brief \ref named-templ-param "Named parameter"
1024 ///function for setting DistMap type
1026 /// \ref named-templ-param "Named parameter"
1027 ///function for setting DistMap type
1030 DfsWizard<DefDistMapBase<T> > distMap(const T &t)
1032 Base::_dist=(void *)&t;
1033 return DfsWizard<DefDistMapBase<T> >(*this);
1036 /// Sets the source node, from which the Dfs algorithm runs.
1038 /// Sets the source node, from which the Dfs algorithm runs.
1039 /// \param s is the source node.
1040 DfsWizard<TR> &source(Node s)
1048 ///Function type interface for Dfs algorithm.
1051 ///Function type interface for Dfs algorithm.
1053 ///This function also has several
1054 ///\ref named-templ-func-param "named parameters",
1055 ///they are declared as the members of class \ref DfsWizard.
1057 ///example shows how to use these parameters.
1059 /// dfs(g,source).predMap(preds).run();
1061 ///\warning Don't forget to put the \ref DfsWizard::run() "run()"
1062 ///to the end of the parameter list.
1066 DfsWizard<DfsWizardBase<GR> >
1067 dfs(const GR &g,typename GR::Node s=INVALID)
1069 return DfsWizard<DfsWizardBase<GR> >(g,s);
1073 /// \brief Visitor class for dfs.
1075 /// It gives a simple interface for a functional interface for dfs
1076 /// traversal. The traversal on a linear data structure.
1077 template <typename _Graph>
1079 typedef _Graph Graph;
1080 typedef typename Graph::Edge Edge;
1081 typedef typename Graph::Node Node;
1082 /// \brief Called when the edge reach a node.
1084 /// It is called when the dfs find an edge which target is not
1086 void discover(const Edge& edge) {}
1087 /// \brief Called when the node reached first time.
1089 /// It is Called when the node reached first time.
1090 void reach(const Node& node) {}
1091 /// \brief Called when we step back on an edge.
1093 /// It is called when the dfs should step back on the edge.
1094 void backtrack(const Edge& edge) {}
1095 /// \brief Called when we step back from the node.
1097 /// It is called when we step back from the node.
1098 void leave(const Node& node) {}
1099 /// \brief Called when the edge examined but target of the edge
1100 /// already discovered.
1102 /// It called when the edge examined but the target of the edge
1103 /// already discovered.
1104 void examine(const Edge& edge) {}
1105 /// \brief Called for the source node of the dfs.
1107 /// It is called for the source node of the dfs.
1108 void start(const Node& node) {}
1109 /// \brief Called when we leave the source node of the dfs.
1111 /// It is called when we leave the source node of the dfs.
1112 void stop(const Node& node) {}
1116 template <typename _Graph>
1118 typedef _Graph Graph;
1119 typedef typename Graph::Edge Edge;
1120 typedef typename Graph::Node Node;
1121 void discover(const Edge&) {}
1122 void reach(const Node&) {}
1123 void backtrack(const Edge&) {}
1124 void leave(const Node&) {}
1125 void examine(const Edge&) {}
1126 void start(const Node&) {}
1127 void stop(const Node&) {}
1129 template <typename _Visitor>
1130 struct Constraints {
1131 void constraints() {
1134 visitor.discover(edge);
1135 visitor.reach(node);
1136 visitor.backtrack(edge);
1137 visitor.leave(node);
1138 visitor.examine(edge);
1139 visitor.start(node);
1147 /// \brief Default traits class of DfsVisit class.
1149 /// Default traits class of DfsVisit class.
1150 /// \param _Graph Graph type.
1151 template<class _Graph>
1152 struct DfsVisitDefaultTraits {
1154 /// \brief The graph type the algorithm runs on.
1155 typedef _Graph Graph;
1157 /// \brief The type of the map that indicates which nodes are reached.
1159 /// The type of the map that indicates which nodes are reached.
1160 /// It must meet the \ref concepts::WriteMap "WriteMap" concept.
1161 /// \todo named parameter to set this type, function to read and write.
1162 typedef typename Graph::template NodeMap<bool> ReachedMap;
1164 /// \brief Instantiates a ReachedMap.
1166 /// This function instantiates a \ref ReachedMap.
1167 /// \param graph is the graph, to which
1168 /// we would like to define the \ref ReachedMap.
1169 static ReachedMap *createReachedMap(const Graph &graph) {
1170 return new ReachedMap(graph);
1175 /// %DFS Visit algorithm class.
1178 /// This class provides an efficient implementation of the %DFS algorithm
1179 /// with visitor interface.
1181 /// The %DfsVisit class provides an alternative interface to the Dfs
1182 /// class. It works with callback mechanism, the DfsVisit object calls
1183 /// on every dfs event the \c Visitor class member functions.
1185 /// \param _Graph The graph type the algorithm runs on. The default value is
1186 /// \ref ListGraph. The value of _Graph is not used directly by Dfs, it
1187 /// is only passed to \ref DfsDefaultTraits.
1188 /// \param _Visitor The Visitor object for the algorithm. The
1189 /// \ref DfsVisitor "DfsVisitor<_Graph>" is an empty Visitor which
1190 /// does not observe the Dfs events. If you want to observe the dfs
1191 /// events you should implement your own Visitor class.
1192 /// \param _Traits Traits class to set various data types used by the
1193 /// algorithm. The default traits class is
1194 /// \ref DfsVisitDefaultTraits "DfsVisitDefaultTraits<_Graph>".
1195 /// See \ref DfsVisitDefaultTraits for the documentation of
1196 /// a Dfs visit traits class.
1198 /// \author Jacint Szabo, Alpar Juttner and Balazs Dezso
1200 template <typename _Graph, typename _Visitor, typename _Traits>
1202 template <typename _Graph = ListGraph,
1203 typename _Visitor = DfsVisitor<_Graph>,
1204 typename _Traits = DfsDefaultTraits<_Graph> >
1209 /// \brief \ref Exception for uninitialized parameters.
1211 /// This error represents problems in the initialization
1212 /// of the parameters of the algorithms.
1213 class UninitializedParameter : public lemon::UninitializedParameter {
1215 virtual const char* what() const throw()
1217 return "lemon::DfsVisit::UninitializedParameter";
1221 typedef _Traits Traits;
1223 typedef typename Traits::Graph Graph;
1225 typedef _Visitor Visitor;
1227 ///The type of the map indicating which nodes are reached.
1228 typedef typename Traits::ReachedMap ReachedMap;
1232 typedef typename Graph::Node Node;
1233 typedef typename Graph::NodeIt NodeIt;
1234 typedef typename Graph::Edge Edge;
1235 typedef typename Graph::OutEdgeIt OutEdgeIt;
1237 /// Pointer to the underlying graph.
1238 const Graph *_graph;
1239 /// Pointer to the visitor object.
1241 ///Pointer to the map of reached status of the nodes.
1242 ReachedMap *_reached;
1243 ///Indicates if \ref _reached is locally allocated (\c true) or not.
1246 std::vector<typename Graph::Edge> _stack;
1249 /// \brief Creates the maps if necessary.
1251 /// Creates the maps if necessary.
1252 void create_maps() {
1254 local_reached = true;
1255 _reached = Traits::createReachedMap(*_graph);
1265 typedef DfsVisit Create;
1267 /// \name Named template parameters
1271 struct DefReachedMapTraits : public Traits {
1272 typedef T ReachedMap;
1273 static ReachedMap *createReachedMap(const Graph &graph) {
1274 throw UninitializedParameter();
1277 /// \brief \ref named-templ-param "Named parameter" for setting
1280 /// \ref named-templ-param "Named parameter" for setting ReachedMap type
1282 struct DefReachedMap : public DfsVisit< Graph, Visitor,
1283 DefReachedMapTraits<T> > {
1284 typedef DfsVisit< Graph, Visitor, DefReachedMapTraits<T> > Create;
1290 /// \brief Constructor.
1294 /// \param graph the graph the algorithm will run on.
1295 /// \param visitor The visitor of the algorithm.
1297 DfsVisit(const Graph& graph, Visitor& visitor)
1298 : _graph(&graph), _visitor(&visitor),
1299 _reached(0), local_reached(false) {}
1301 /// \brief Destructor.
1305 if(local_reached) delete _reached;
1308 /// \brief Sets the map indicating if a node is reached.
1310 /// Sets the map indicating if a node is reached.
1311 /// If you don't use this function before calling \ref run(),
1312 /// it will allocate one. The destuctor deallocates this
1313 /// automatically allocated map, of course.
1314 /// \return <tt> (*this) </tt>
1315 DfsVisit &reachedMap(ReachedMap &m) {
1318 local_reached=false;
1325 /// \name Execution control
1326 /// The simplest way to execute the algorithm is to use
1327 /// one of the member functions called \c run(...).
1329 /// If you need more control on the execution,
1330 /// first you must call \ref init(), then you can adda source node
1331 /// with \ref addSource().
1332 /// Finally \ref start() will perform the actual path
1336 /// \brief Initializes the internal data structures.
1338 /// Initializes the internal data structures.
1342 _stack.resize(countNodes(*_graph));
1344 for (NodeIt u(*_graph) ; u != INVALID ; ++u) {
1345 _reached->set(u, false);
1349 /// \brief Adds a new source node.
1351 /// Adds a new source node to the set of nodes to be processed.
1352 void addSource(Node s) {
1353 if(!(*_reached)[s]) {
1354 _reached->set(s,true);
1358 _graph->firstOut(e, s);
1360 _stack[++_stack_head] = e;
1367 /// \brief Processes the next edge.
1369 /// Processes the next edge.
1371 /// \return The processed edge.
1373 /// \pre The stack must not be empty!
1374 Edge processNextEdge() {
1375 Edge e = _stack[_stack_head];
1376 Node m = _graph->target(e);
1377 if(!(*_reached)[m]) {
1378 _visitor->discover(e);
1380 _reached->set(m, true);
1381 _graph->firstOut(_stack[++_stack_head], m);
1383 _visitor->examine(e);
1384 m = _graph->source(e);
1385 _graph->nextOut(_stack[_stack_head]);
1387 while (_stack_head>=0 && _stack[_stack_head] == INVALID) {
1390 if (_stack_head >= 0) {
1391 _visitor->backtrack(_stack[_stack_head]);
1392 m = _graph->source(_stack[_stack_head]);
1393 _graph->nextOut(_stack[_stack_head]);
1401 /// \brief Next edge to be processed.
1403 /// Next edge to be processed.
1405 /// \return The next edge to be processed or INVALID if the stack is
1408 return _stack_head >= 0 ? _stack[_stack_head] : INVALID;
1411 /// \brief Returns \c false if there are nodes
1412 /// to be processed in the queue
1414 /// Returns \c false if there are nodes
1415 /// to be processed in the queue
1416 bool emptyQueue() { return _stack_head < 0; }
1418 /// \brief Returns the number of the nodes to be processed.
1420 /// Returns the number of the nodes to be processed in the queue.
1421 int queueSize() { return _stack_head + 1; }
1423 /// \brief Executes the algorithm.
1425 /// Executes the algorithm.
1427 /// \pre init() must be called and at least one node should be added
1428 /// with addSource() before using this function.
1430 while ( !emptyQueue() ) processNextEdge();
1433 /// \brief Executes the algorithm until \c dest is reached.
1435 /// Executes the algorithm until \c dest is reached.
1437 /// \pre init() must be called and at least one node should be added
1438 /// with addSource() before using this function.
1439 void start(Node dest) {
1440 while ( !emptyQueue() && _graph->target(_stack[_stack_head]) != dest)
1444 /// \brief Executes the algorithm until a condition is met.
1446 /// Executes the algorithm until a condition is met.
1448 /// \pre init() must be called and at least one node should be added
1449 /// with addSource() before using this function.
1451 /// \param em must be a bool (or convertible) edge map. The algorithm
1452 /// will stop when it reaches an edge \c e with \code nm[e]==true \endcode.
1454 /// \warning Contrary to \ref Dfs and \ref Dijkstra, \c em is an edge map,
1456 template <typename EM>
1457 void start(const EM &em) {
1458 while (!emptyQueue() && !em[_stack[_stack_head]]) processNextEdge();
1461 /// \brief Runs %DFSVisit algorithm from node \c s.
1463 /// This method runs the %DFS algorithm from a root node \c s.
1464 /// \note d.run(s) is just a shortcut of the following code.
1476 /// \brief Runs %DFSVisit algorithm to visit all nodes in the graph.
1478 /// This method runs the %DFS algorithm in order to
1479 /// compute the %DFS path to each node. The algorithm computes
1480 /// - The %DFS tree.
1481 /// - The distance of each node from the root in the %DFS tree.
1483 ///\note d.run() is just a shortcut of the following code.
1486 /// for (NodeIt it(graph); it != INVALID; ++it) {
1487 /// if (!d.reached(it)) {
1488 /// d.addSource(it);
1495 for (NodeIt it(*_graph); it != INVALID; ++it) {
1504 /// \name Query Functions
1505 /// The result of the %DFS algorithm can be obtained using these
1507 /// Before the use of these functions,
1508 /// either run() or start() must be called.
1510 /// \brief Checks if a node is reachable from the root.
1512 /// Returns \c true if \c v is reachable from the root(s).
1513 /// \warning The source nodes are inditated as unreachable.
1514 /// \pre Either \ref run() or \ref start()
1515 /// must be called before using this function.
1517 bool reached(Node v) { return (*_reached)[v]; }
1522 } //END OF NAMESPACE LEMON