Small improvement in documentation.
3 * This file is a part of LEMON, a generic C++ optimization library
5 * Copyright (C) 2003-2007
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 <tt>em[e]<\tt> true.
569 ///\return The reached edge \c e with <tt>em[e]<\tt> true or
570 ///\c INVALID if no such edge was found.
572 ///\warning Contrary to \ref Bfs and \ref Dijkstra, \c em is an edge map,
575 Edge start(const EM &em)
577 while ( !emptyQueue() && !em[_stack[_stack_head]] )
579 return emptyQueue() ? INVALID : _stack[_stack_head];
582 ///Runs %DFS algorithm to visit all nodes in the graph.
584 ///This method runs the %DFS algorithm in order to
586 ///%DFS path to each node. The algorithm computes
588 ///- The distance of each node from the root in the %DFS tree.
590 ///\note d.run() is just a shortcut of the following code.
593 /// for (NodeIt it(graph); it != INVALID; ++it) {
594 /// if (!d.reached(it)) {
602 for (NodeIt it(*G); it != INVALID; ++it) {
610 ///Runs %DFS algorithm from node \c s.
612 ///This method runs the %DFS algorithm from a root node \c s
615 ///%DFS path to each node. The algorithm computes
617 ///- The distance of each node from the root in the %DFS tree.
619 ///\note d.run(s) is just a shortcut of the following code.
631 ///Finds the %DFS path between \c s and \c t.
633 ///Finds the %DFS path between \c s and \c t.
635 ///\return The length of the %DFS s---t path if there exists one,
637 ///\note Apart from the return value, d.run(s,t) is
638 ///just a shortcut of the following code.
644 int run(Node s,Node t) {
648 return reached(t)?_stack_head+1:0;
653 ///\name Query Functions
654 ///The result of the %DFS algorithm can be obtained using these
656 ///Before the use of these functions,
657 ///either run() or start() must be called.
661 typedef PredMapPath<Graph, PredMap> Path;
663 ///Gives back the shortest path.
665 ///Gives back the shortest path.
666 ///\pre The \c t should be reachable from the source.
669 return Path(*G, *_pred, t);
672 ///The distance of a node from the root(s).
674 ///Returns the distance of a node from the root(s).
675 ///\pre \ref run() must be called before using this function.
676 ///\warning If node \c v is unreachable from the root(s) then the return
677 ///value of this funcion is undefined.
678 int dist(Node v) const { return (*_dist)[v]; }
680 ///Returns the 'previous edge' of the %DFS tree.
682 ///For a node \c v it returns the 'previous edge'
684 ///i.e. it returns the last edge of a %DFS path from the root(s) to \c
685 ///v. It is \ref INVALID
686 ///if \c v is unreachable from the root(s) or \c v is a root. The
687 ///%DFS tree used here is equal to the %DFS tree used in
689 ///\pre Either \ref run() or \ref start() must be called before using
691 Edge predEdge(Node v) const { return (*_pred)[v];}
693 ///Returns the 'previous node' of the %DFS tree.
695 ///For a node \c v it returns the 'previous node'
697 ///i.e. it returns the last but one node from a %DFS path from the
699 ///It is INVALID if \c v is unreachable from the root(s) or
700 ///if \c v itself a root.
701 ///The %DFS tree used here is equal to the %DFS
702 ///tree used in \ref predEdge().
703 ///\pre Either \ref run() or \ref start() must be called before
704 ///using this function.
705 Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
706 G->source((*_pred)[v]); }
708 ///Returns a reference to the NodeMap of distances.
710 ///Returns a reference to the NodeMap of distances.
711 ///\pre Either \ref run() or \ref init() must
712 ///be called before using this function.
713 const DistMap &distMap() const { return *_dist;}
715 ///Returns a reference to the %DFS edge-tree map.
717 ///Returns a reference to the NodeMap of the edges of the
719 ///\pre Either \ref run() or \ref init()
720 ///must be called before using this function.
721 const PredMap &predMap() const { return *_pred;}
723 ///Checks if a node is reachable from the root.
725 ///Returns \c true if \c v is reachable from the root(s).
726 ///\warning The source nodes are inditated as unreachable.
727 ///\pre Either \ref run() or \ref start()
728 ///must be called before using this function.
730 bool reached(Node v) { return (*_reached)[v]; }
735 ///Default traits class of Dfs function.
737 ///Default traits class of Dfs function.
738 ///\param GR Graph type.
740 struct DfsWizardDefaultTraits
742 ///The graph type the algorithm runs on.
744 ///\brief The type of the map that stores the last
745 ///edges of the %DFS paths.
747 ///The type of the map that stores the last
748 ///edges of the %DFS paths.
749 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
751 typedef NullMap<typename Graph::Node,typename GR::Edge> PredMap;
752 ///Instantiates a PredMap.
754 ///This function instantiates a \ref PredMap.
755 ///\param g is the graph, to which we would like to define the PredMap.
756 ///\todo The graph alone may be insufficient to initialize
758 static PredMap *createPredMap(const GR &g)
760 static PredMap *createPredMap(const GR &)
763 return new PredMap();
766 ///The type of the map that indicates which nodes are processed.
768 ///The type of the map that indicates which nodes are processed.
769 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
770 ///\todo named parameter to set this type, function to read and write.
771 typedef NullMap<typename Graph::Node,bool> ProcessedMap;
772 ///Instantiates a ProcessedMap.
774 ///This function instantiates a \ref ProcessedMap.
775 ///\param g is the graph, to which
776 ///we would like to define the \ref ProcessedMap
778 static ProcessedMap *createProcessedMap(const GR &g)
780 static ProcessedMap *createProcessedMap(const GR &)
783 return new ProcessedMap();
785 ///The type of the map that indicates which nodes are reached.
787 ///The type of the map that indicates which nodes are reached.
788 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
789 ///\todo named parameter to set this type, function to read and write.
790 typedef typename Graph::template NodeMap<bool> ReachedMap;
791 ///Instantiates a ReachedMap.
793 ///This function instantiates a \ref ReachedMap.
794 ///\param G is the graph, to which
795 ///we would like to define the \ref ReachedMap.
796 static ReachedMap *createReachedMap(const GR &G)
798 return new ReachedMap(G);
800 ///The type of the map that stores the dists of the nodes.
802 ///The type of the map that stores the dists of the nodes.
803 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
805 typedef NullMap<typename Graph::Node,int> DistMap;
806 ///Instantiates a DistMap.
808 ///This function instantiates a \ref DistMap.
809 ///\param g is the graph, to which we would like to define the \ref DistMap
811 static DistMap *createDistMap(const GR &g)
813 static DistMap *createDistMap(const GR &)
816 return new DistMap();
820 /// Default traits used by \ref DfsWizard
822 /// To make it easier to use Dfs algorithm
823 ///we have created a wizard class.
824 /// This \ref DfsWizard class needs default traits,
825 ///as well as the \ref Dfs class.
826 /// The \ref DfsWizardBase is a class to be the default traits of the
827 /// \ref DfsWizard class.
829 class DfsWizardBase : public DfsWizardDefaultTraits<GR>
832 typedef DfsWizardDefaultTraits<GR> Base;
834 /// Type of the nodes in the graph.
835 typedef typename Base::Graph::Node Node;
837 /// Pointer to the underlying graph.
839 ///Pointer to the map of reached nodes.
841 ///Pointer to the map of processed nodes.
843 ///Pointer to the map of predecessors edges.
845 ///Pointer to the map of distances.
847 ///Pointer to the source node.
853 /// This constructor does not require parameters, therefore it initiates
854 /// all of the attributes to default values (0, INVALID).
855 DfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0),
856 _dist(0), _source(INVALID) {}
860 /// This constructor requires some parameters,
861 /// listed in the parameters list.
862 /// Others are initiated to 0.
863 /// \param g is the initial value of \ref _g
864 /// \param s is the initial value of \ref _source
865 DfsWizardBase(const GR &g, Node s=INVALID) :
866 _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
867 _reached(0), _processed(0), _pred(0), _dist(0), _source(s) {}
871 /// A class to make the usage of the Dfs algorithm easier
873 /// This class is created to make it easier to use the Dfs algorithm.
874 /// It uses the functions and features of the plain \ref Dfs,
875 /// but it is much simpler to use it.
877 /// Simplicity means that the way to change the types defined
878 /// in the traits class is based on functions that returns the new class
879 /// and not on templatable built-in classes.
880 /// When using the plain \ref Dfs
881 /// the new class with the modified type comes from
882 /// the original class by using the ::
883 /// operator. In the case of \ref DfsWizard only
884 /// a function have to be called and it will
885 /// return the needed class.
887 /// It does not have own \ref run method. When its \ref run method is called
888 /// it initiates a plain \ref Dfs object, and calls the \ref Dfs::run
891 class DfsWizard : public TR
895 ///The type of the underlying graph.
896 typedef typename TR::Graph Graph;
898 typedef typename Graph::Node Node;
900 typedef typename Graph::NodeIt NodeIt;
902 typedef typename Graph::Edge Edge;
904 typedef typename Graph::OutEdgeIt OutEdgeIt;
906 ///\brief The type of the map that stores
908 typedef typename TR::ReachedMap ReachedMap;
909 ///\brief The type of the map that stores
910 ///the processed nodes
911 typedef typename TR::ProcessedMap ProcessedMap;
912 ///\brief The type of the map that stores the last
913 ///edges of the %DFS paths.
914 typedef typename TR::PredMap PredMap;
915 ///The type of the map that stores the distances of the nodes.
916 typedef typename TR::DistMap DistMap;
920 DfsWizard() : TR() {}
922 /// Constructor that requires parameters.
924 /// Constructor that requires parameters.
925 /// These parameters will be the default values for the traits class.
926 DfsWizard(const Graph &g, Node s=INVALID) :
930 DfsWizard(const TR &b) : TR(b) {}
934 ///Runs Dfs algorithm from a given node.
936 ///Runs Dfs algorithm from a given node.
937 ///The node can be given by the \ref source function.
940 if(Base::_source==INVALID) throw UninitializedParameter();
941 Dfs<Graph,TR> alg(*reinterpret_cast<const Graph*>(Base::_g));
943 alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
945 alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
947 alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
949 alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
950 alg.run(Base::_source);
953 ///Runs Dfs algorithm from the given node.
955 ///Runs Dfs algorithm from the given node.
956 ///\param s is the given source.
964 struct DefPredMapBase : public Base {
966 static PredMap *createPredMap(const Graph &) { return 0; };
967 DefPredMapBase(const TR &b) : TR(b) {}
970 ///\brief \ref named-templ-param "Named parameter"
971 ///function for setting PredMap type
973 /// \ref named-templ-param "Named parameter"
974 ///function for setting PredMap type
977 DfsWizard<DefPredMapBase<T> > predMap(const T &t)
979 Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
980 return DfsWizard<DefPredMapBase<T> >(*this);
985 struct DefReachedMapBase : public Base {
986 typedef T ReachedMap;
987 static ReachedMap *createReachedMap(const Graph &) { return 0; };
988 DefReachedMapBase(const TR &b) : TR(b) {}
991 ///\brief \ref named-templ-param "Named parameter"
992 ///function for setting ReachedMap
994 /// \ref named-templ-param "Named parameter"
995 ///function for setting ReachedMap
998 DfsWizard<DefReachedMapBase<T> > reachedMap(const T &t)
1000 Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1001 return DfsWizard<DefReachedMapBase<T> >(*this);
1006 struct DefProcessedMapBase : public Base {
1007 typedef T ProcessedMap;
1008 static ProcessedMap *createProcessedMap(const Graph &) { return 0; };
1009 DefProcessedMapBase(const TR &b) : TR(b) {}
1012 ///\brief \ref named-templ-param "Named parameter"
1013 ///function for setting ProcessedMap
1015 /// \ref named-templ-param "Named parameter"
1016 ///function for setting ProcessedMap
1019 DfsWizard<DefProcessedMapBase<T> > processedMap(const T &t)
1021 Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1022 return DfsWizard<DefProcessedMapBase<T> >(*this);
1026 struct DefDistMapBase : public Base {
1028 static DistMap *createDistMap(const Graph &) { return 0; };
1029 DefDistMapBase(const TR &b) : TR(b) {}
1032 ///\brief \ref named-templ-param "Named parameter"
1033 ///function for setting DistMap type
1035 /// \ref named-templ-param "Named parameter"
1036 ///function for setting DistMap type
1039 DfsWizard<DefDistMapBase<T> > distMap(const T &t)
1041 Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1042 return DfsWizard<DefDistMapBase<T> >(*this);
1045 /// Sets the source node, from which the Dfs algorithm runs.
1047 /// Sets the source node, from which the Dfs algorithm runs.
1048 /// \param s is the source node.
1049 DfsWizard<TR> &source(Node s)
1057 ///Function type interface for Dfs algorithm.
1060 ///Function type interface for Dfs algorithm.
1062 ///This function also has several
1063 ///\ref named-templ-func-param "named parameters",
1064 ///they are declared as the members of class \ref DfsWizard.
1066 ///example shows how to use these parameters.
1068 /// dfs(g,source).predMap(preds).run();
1070 ///\warning Don't forget to put the \ref DfsWizard::run() "run()"
1071 ///to the end of the parameter list.
1075 DfsWizard<DfsWizardBase<GR> >
1076 dfs(const GR &g,typename GR::Node s=INVALID)
1078 return DfsWizard<DfsWizardBase<GR> >(g,s);
1082 /// \brief Visitor class for dfs.
1084 /// It gives a simple interface for a functional interface for dfs
1085 /// traversal. The traversal on a linear data structure.
1086 template <typename _Graph>
1088 typedef _Graph Graph;
1089 typedef typename Graph::Edge Edge;
1090 typedef typename Graph::Node Node;
1091 /// \brief Called when the edge reach a node.
1093 /// It is called when the dfs find an edge which target is not
1095 void discover(const Edge& edge) {}
1096 /// \brief Called when the node reached first time.
1098 /// It is Called when the node reached first time.
1099 void reach(const Node& node) {}
1100 /// \brief Called when we step back on an edge.
1102 /// It is called when the dfs should step back on the edge.
1103 void backtrack(const Edge& edge) {}
1104 /// \brief Called when we step back from the node.
1106 /// It is called when we step back from the node.
1107 void leave(const Node& node) {}
1108 /// \brief Called when the edge examined but target of the edge
1109 /// already discovered.
1111 /// It called when the edge examined but the target of the edge
1112 /// already discovered.
1113 void examine(const Edge& edge) {}
1114 /// \brief Called for the source node of the dfs.
1116 /// It is called for the source node of the dfs.
1117 void start(const Node& node) {}
1118 /// \brief Called when we leave the source node of the dfs.
1120 /// It is called when we leave the source node of the dfs.
1121 void stop(const Node& node) {}
1125 template <typename _Graph>
1127 typedef _Graph Graph;
1128 typedef typename Graph::Edge Edge;
1129 typedef typename Graph::Node Node;
1130 void discover(const Edge&) {}
1131 void reach(const Node&) {}
1132 void backtrack(const Edge&) {}
1133 void leave(const Node&) {}
1134 void examine(const Edge&) {}
1135 void start(const Node&) {}
1136 void stop(const Node&) {}
1138 template <typename _Visitor>
1139 struct Constraints {
1140 void constraints() {
1143 visitor.discover(edge);
1144 visitor.reach(node);
1145 visitor.backtrack(edge);
1146 visitor.leave(node);
1147 visitor.examine(edge);
1148 visitor.start(node);
1156 /// \brief Default traits class of DfsVisit class.
1158 /// Default traits class of DfsVisit class.
1159 /// \param _Graph Graph type.
1160 template<class _Graph>
1161 struct DfsVisitDefaultTraits {
1163 /// \brief The graph type the algorithm runs on.
1164 typedef _Graph Graph;
1166 /// \brief The type of the map that indicates which nodes are reached.
1168 /// The type of the map that indicates which nodes are reached.
1169 /// It must meet the \ref concepts::WriteMap "WriteMap" concept.
1170 /// \todo named parameter to set this type, function to read and write.
1171 typedef typename Graph::template NodeMap<bool> ReachedMap;
1173 /// \brief Instantiates a ReachedMap.
1175 /// This function instantiates a \ref ReachedMap.
1176 /// \param graph is the graph, to which
1177 /// we would like to define the \ref ReachedMap.
1178 static ReachedMap *createReachedMap(const Graph &graph) {
1179 return new ReachedMap(graph);
1184 /// %DFS Visit algorithm class.
1187 /// This class provides an efficient implementation of the %DFS algorithm
1188 /// with visitor interface.
1190 /// The %DfsVisit class provides an alternative interface to the Dfs
1191 /// class. It works with callback mechanism, the DfsVisit object calls
1192 /// on every dfs event the \c Visitor class member functions.
1194 /// \param _Graph The graph type the algorithm runs on. The default value is
1195 /// \ref ListGraph. The value of _Graph is not used directly by Dfs, it
1196 /// is only passed to \ref DfsDefaultTraits.
1197 /// \param _Visitor The Visitor object for the algorithm. The
1198 /// \ref DfsVisitor "DfsVisitor<_Graph>" is an empty Visitor which
1199 /// does not observe the Dfs events. If you want to observe the dfs
1200 /// events you should implement your own Visitor class.
1201 /// \param _Traits Traits class to set various data types used by the
1202 /// algorithm. The default traits class is
1203 /// \ref DfsVisitDefaultTraits "DfsVisitDefaultTraits<_Graph>".
1204 /// See \ref DfsVisitDefaultTraits for the documentation of
1205 /// a Dfs visit traits class.
1207 /// \author Jacint Szabo, Alpar Juttner and Balazs Dezso
1209 template <typename _Graph, typename _Visitor, typename _Traits>
1211 template <typename _Graph = ListGraph,
1212 typename _Visitor = DfsVisitor<_Graph>,
1213 typename _Traits = DfsDefaultTraits<_Graph> >
1218 /// \brief \ref Exception for uninitialized parameters.
1220 /// This error represents problems in the initialization
1221 /// of the parameters of the algorithms.
1222 class UninitializedParameter : public lemon::UninitializedParameter {
1224 virtual const char* what() const throw()
1226 return "lemon::DfsVisit::UninitializedParameter";
1230 typedef _Traits Traits;
1232 typedef typename Traits::Graph Graph;
1234 typedef _Visitor Visitor;
1236 ///The type of the map indicating which nodes are reached.
1237 typedef typename Traits::ReachedMap ReachedMap;
1241 typedef typename Graph::Node Node;
1242 typedef typename Graph::NodeIt NodeIt;
1243 typedef typename Graph::Edge Edge;
1244 typedef typename Graph::OutEdgeIt OutEdgeIt;
1246 /// Pointer to the underlying graph.
1247 const Graph *_graph;
1248 /// Pointer to the visitor object.
1250 ///Pointer to the map of reached status of the nodes.
1251 ReachedMap *_reached;
1252 ///Indicates if \ref _reached is locally allocated (\c true) or not.
1255 std::vector<typename Graph::Edge> _stack;
1258 /// \brief Creates the maps if necessary.
1260 /// Creates the maps if necessary.
1261 void create_maps() {
1263 local_reached = true;
1264 _reached = Traits::createReachedMap(*_graph);
1274 typedef DfsVisit Create;
1276 /// \name Named template parameters
1280 struct DefReachedMapTraits : public Traits {
1281 typedef T ReachedMap;
1282 static ReachedMap *createReachedMap(const Graph &graph) {
1283 throw UninitializedParameter();
1286 /// \brief \ref named-templ-param "Named parameter" for setting
1289 /// \ref named-templ-param "Named parameter" for setting ReachedMap type
1291 struct DefReachedMap : public DfsVisit< Graph, Visitor,
1292 DefReachedMapTraits<T> > {
1293 typedef DfsVisit< Graph, Visitor, DefReachedMapTraits<T> > Create;
1299 /// \brief Constructor.
1303 /// \param graph the graph the algorithm will run on.
1304 /// \param visitor The visitor of the algorithm.
1306 DfsVisit(const Graph& graph, Visitor& visitor)
1307 : _graph(&graph), _visitor(&visitor),
1308 _reached(0), local_reached(false) {}
1310 /// \brief Destructor.
1314 if(local_reached) delete _reached;
1317 /// \brief Sets the map indicating if a node is reached.
1319 /// Sets the map indicating if a node is reached.
1320 /// If you don't use this function before calling \ref run(),
1321 /// it will allocate one. The destuctor deallocates this
1322 /// automatically allocated map, of course.
1323 /// \return <tt> (*this) </tt>
1324 DfsVisit &reachedMap(ReachedMap &m) {
1327 local_reached=false;
1334 /// \name Execution control
1335 /// The simplest way to execute the algorithm is to use
1336 /// one of the member functions called \c run(...).
1338 /// If you need more control on the execution,
1339 /// first you must call \ref init(), then you can adda source node
1340 /// with \ref addSource().
1341 /// Finally \ref start() will perform the actual path
1345 /// \brief Initializes the internal data structures.
1347 /// Initializes the internal data structures.
1351 _stack.resize(countNodes(*_graph));
1353 for (NodeIt u(*_graph) ; u != INVALID ; ++u) {
1354 _reached->set(u, false);
1358 /// \brief Adds a new source node.
1360 /// Adds a new source node to the set of nodes to be processed.
1361 void addSource(Node s) {
1362 if(!(*_reached)[s]) {
1363 _reached->set(s,true);
1367 _graph->firstOut(e, s);
1369 _stack[++_stack_head] = e;
1376 /// \brief Processes the next edge.
1378 /// Processes the next edge.
1380 /// \return The processed edge.
1382 /// \pre The stack must not be empty!
1383 Edge processNextEdge() {
1384 Edge e = _stack[_stack_head];
1385 Node m = _graph->target(e);
1386 if(!(*_reached)[m]) {
1387 _visitor->discover(e);
1389 _reached->set(m, true);
1390 _graph->firstOut(_stack[++_stack_head], m);
1392 _visitor->examine(e);
1393 m = _graph->source(e);
1394 _graph->nextOut(_stack[_stack_head]);
1396 while (_stack_head>=0 && _stack[_stack_head] == INVALID) {
1399 if (_stack_head >= 0) {
1400 _visitor->backtrack(_stack[_stack_head]);
1401 m = _graph->source(_stack[_stack_head]);
1402 _graph->nextOut(_stack[_stack_head]);
1410 /// \brief Next edge to be processed.
1412 /// Next edge to be processed.
1414 /// \return The next edge to be processed or INVALID if the stack is
1417 return _stack_head >= 0 ? _stack[_stack_head] : INVALID;
1420 /// \brief Returns \c false if there are nodes
1421 /// to be processed in the queue
1423 /// Returns \c false if there are nodes
1424 /// to be processed in the queue
1425 bool emptyQueue() { return _stack_head < 0; }
1427 /// \brief Returns the number of the nodes to be processed.
1429 /// Returns the number of the nodes to be processed in the queue.
1430 int queueSize() { return _stack_head + 1; }
1432 /// \brief Executes the algorithm.
1434 /// Executes the algorithm.
1436 /// \pre init() must be called and at least one node should be added
1437 /// with addSource() before using this function.
1439 while ( !emptyQueue() ) processNextEdge();
1442 /// \brief Executes the algorithm until \c dest is reached.
1444 /// Executes the algorithm until \c dest is reached.
1446 /// \pre init() must be called and at least one node should be added
1447 /// with addSource() before using this function.
1448 void start(Node dest) {
1449 while ( !emptyQueue() && _graph->target(_stack[_stack_head]) != dest )
1453 /// \brief Executes the algorithm until a condition is met.
1455 /// Executes the algorithm until a condition is met.
1457 /// \pre init() must be called and at least one node should be added
1458 /// with addSource() before using this function.
1460 /// \param em must be a bool (or convertible) edge map. The algorithm
1461 /// will stop when it reaches an edge \c e with <tt>em[e]<\tt> true.
1463 ///\return The reached edge \c e with <tt>em[e]<\tt> true or
1464 ///\c INVALID if no such edge was found.
1466 /// \warning Contrary to \ref Bfs and \ref Dijkstra, \c em is an edge map,
1468 template <typename EM>
1469 Edge start(const EM &em) {
1470 while ( !emptyQueue() && !em[_stack[_stack_head]] )
1472 return emptyQueue() ? INVALID : _stack[_stack_head];
1475 /// \brief Runs %DFSVisit algorithm from node \c s.
1477 /// This method runs the %DFS algorithm from a root node \c s.
1478 /// \note d.run(s) is just a shortcut of the following code.
1490 /// \brief Runs %DFSVisit algorithm to visit all nodes in the graph.
1492 /// This method runs the %DFS algorithm in order to
1493 /// compute the %DFS path to each node. The algorithm computes
1494 /// - The %DFS tree.
1495 /// - The distance of each node from the root in the %DFS tree.
1497 ///\note d.run() is just a shortcut of the following code.
1500 /// for (NodeIt it(graph); it != INVALID; ++it) {
1501 /// if (!d.reached(it)) {
1502 /// d.addSource(it);
1509 for (NodeIt it(*_graph); it != INVALID; ++it) {
1518 /// \name Query Functions
1519 /// The result of the %DFS algorithm can be obtained using these
1521 /// Before the use of these functions,
1522 /// either run() or start() must be called.
1524 /// \brief Checks if a node is reachable from the root.
1526 /// Returns \c true if \c v is reachable from the root(s).
1527 /// \warning The source nodes are inditated as unreachable.
1528 /// \pre Either \ref run() or \ref start()
1529 /// must be called before using this function.
1531 bool reached(Node v) { return (*_reached)[v]; }
1536 } //END OF NAMESPACE LEMON