Various improvements in NetworkSimplex.
- Faster variant of "Altering Candidate List" pivot rule using make_heap
instead of partial_sort.
- Doc improvements.
- Removing unecessary inline keywords.
3 * This file is a part of LEMON, a generic C++ optimization library
5 * Copyright (C) 2003-2008
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
9 * Permission to use, modify and distribute this software is granted
10 * provided that this copyright notice appears in all copies. For
11 * precise terms see the accompanying LICENSE file.
13 * This software is provided "AS IS" with no warranty of any kind,
14 * express or implied, and with no claim as to its suitability for any
24 ///\brief Dfs algorithm.
26 #include <lemon/list_graph.h>
27 #include <lemon/graph_utils.h>
28 #include <lemon/bits/path_dump.h>
29 #include <lemon/bits/invalid.h>
30 #include <lemon/error.h>
31 #include <lemon/maps.h>
33 #include <lemon/concept_check.h>
38 ///Default traits class of Dfs class.
40 ///Default traits class of Dfs class.
41 ///\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 ///\brief \ref named-templ-param "Named parameter" for setting
242 ///\ref named-templ-param "Named parameter" for setting PredMap type
245 struct DefPredMap : public Dfs<Graph, DefPredMapTraits<T> > {
246 typedef Dfs<Graph, DefPredMapTraits<T> > Create;
251 struct DefDistMapTraits : public Traits {
253 static DistMap *createDistMap(const Graph &)
255 throw UninitializedParameter();
258 ///\brief \ref named-templ-param "Named parameter" for setting
261 ///\ref named-templ-param "Named parameter" for setting DistMap
265 typedef Dfs<Graph, DefDistMapTraits<T> > Create;
269 struct DefReachedMapTraits : public Traits {
270 typedef T ReachedMap;
271 static ReachedMap *createReachedMap(const Graph &)
273 throw UninitializedParameter();
276 ///\brief \ref named-templ-param "Named parameter" for setting
279 ///\ref named-templ-param "Named parameter" for setting ReachedMap type
282 struct DefReachedMap : public Dfs< Graph, DefReachedMapTraits<T> > {
283 typedef Dfs< Graph, DefReachedMapTraits<T> > Create;
287 struct DefProcessedMapTraits : public Traits {
288 typedef T ProcessedMap;
289 static ProcessedMap *createProcessedMap(const Graph &)
291 throw UninitializedParameter();
294 ///\brief \ref named-templ-param "Named parameter" for setting
297 ///\ref named-templ-param "Named parameter" for setting ProcessedMap type
300 struct DefProcessedMap : public Dfs< Graph, DefProcessedMapTraits<T> > {
301 typedef Dfs< Graph, DefProcessedMapTraits<T> > Create;
304 struct DefGraphProcessedMapTraits : public Traits {
305 typedef typename Graph::template NodeMap<bool> ProcessedMap;
306 static ProcessedMap *createProcessedMap(const Graph &G)
308 return new ProcessedMap(G);
311 ///\brief \ref named-templ-param "Named parameter"
312 ///for setting the ProcessedMap type to be Graph::NodeMap<bool>.
314 ///\ref named-templ-param "Named parameter"
315 ///for setting the ProcessedMap type to be Graph::NodeMap<bool>.
316 ///If you don't set it explicitely, it will be automatically allocated.
318 class DefProcessedMapToBeDefaultMap :
319 public Dfs< Graph, DefGraphProcessedMapTraits> {
320 typedef Dfs< Graph, DefGraphProcessedMapTraits> Create;
329 ///\param _G the graph the algorithm will run on.
331 Dfs(const Graph& _G) :
333 _pred(NULL), local_pred(false),
334 _dist(NULL), local_dist(false),
335 _reached(NULL), local_reached(false),
336 _processed(NULL), local_processed(false)
342 if(local_pred) delete _pred;
343 if(local_dist) delete _dist;
344 if(local_reached) delete _reached;
345 if(local_processed) delete _processed;
348 ///Sets the map storing the predecessor edges.
350 ///Sets the map storing the predecessor edges.
351 ///If you don't use this function before calling \ref run(),
352 ///it will allocate one. The destuctor deallocates this
353 ///automatically allocated map, of course.
354 ///\return <tt> (*this) </tt>
355 Dfs &predMap(PredMap &m)
365 ///Sets the map storing the distances calculated by the algorithm.
367 ///Sets the map storing the distances calculated by the algorithm.
368 ///If you don't use this function before calling \ref run(),
369 ///it will allocate one. The destuctor deallocates this
370 ///automatically allocated map, of course.
371 ///\return <tt> (*this) </tt>
372 Dfs &distMap(DistMap &m)
382 ///Sets the map indicating if a node is reached.
384 ///Sets the map indicating if a node is reached.
385 ///If you don't use this function before calling \ref run(),
386 ///it will allocate one. The destuctor deallocates this
387 ///automatically allocated map, of course.
388 ///\return <tt> (*this) </tt>
389 Dfs &reachedMap(ReachedMap &m)
399 ///Sets the map indicating if a node is processed.
401 ///Sets the map indicating if a node is processed.
402 ///If you don't use this function before calling \ref run(),
403 ///it will allocate one. The destuctor deallocates this
404 ///automatically allocated map, of course.
405 ///\return <tt> (*this) </tt>
406 Dfs &processedMap(ProcessedMap &m)
408 if(local_processed) {
410 local_processed=false;
417 ///\name Execution control
418 ///The simplest way to execute the algorithm is to use
419 ///one of the member functions called \c run(...).
421 ///If you need more control on the execution,
422 ///first you must call \ref init(), then you can add a source node
423 ///with \ref addSource().
424 ///Finally \ref start() will perform the actual path
429 ///Initializes the internal data structures.
431 ///Initializes the internal data structures.
436 _stack.resize(countNodes(*G));
438 for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
439 _pred->set(u,INVALID);
440 // _predNode->set(u,INVALID);
441 _reached->set(u,false);
442 _processed->set(u,false);
446 ///Adds a new source node.
448 ///Adds a new source node to the set of nodes to be processed.
450 ///\warning dists are wrong (or at least strange)
451 ///in case of multiple sources.
452 void addSource(Node s)
456 _reached->set(s,true);
457 _pred->set(s,INVALID);
460 _stack[++_stack_head]=e;
461 _dist->set(s,_stack_head);
464 _processed->set(s,true);
470 ///Processes the next edge.
472 ///Processes the next edge.
474 ///\return The processed edge.
476 ///\pre The stack must not be empty!
477 Edge processNextEdge()
480 Edge e=_stack[_stack_head];
481 if(!(*_reached)[m=G->target(e)]) {
483 _reached->set(m,true);
485 _stack[_stack_head] = OutEdgeIt(*G, m);
486 _dist->set(m,_stack_head);
490 ++_stack[_stack_head];
492 while(_stack_head>=0 && _stack[_stack_head]==INVALID) {
493 _processed->set(m,true);
496 m=G->source(_stack[_stack_head]);
497 ++_stack[_stack_head];
502 ///Next edge to be processed.
504 ///Next edge to be processed.
506 ///\return The next edge to be processed or INVALID if the stack is
510 return _stack_head>=0?_stack[_stack_head]:INVALID;
513 ///\brief Returns \c false if there are nodes
514 ///to be processed in the queue
516 ///Returns \c false if there are nodes
517 ///to be processed in the queue
518 bool emptyQueue() { return _stack_head<0; }
519 ///Returns the number of the nodes to be processed.
521 ///Returns the number of the nodes to be processed in the queue.
522 int queueSize() { return _stack_head+1; }
524 ///Executes the algorithm.
526 ///Executes the algorithm.
528 ///\pre init() must be called and at least one node should be added
529 ///with addSource() before using this function.
531 ///This method runs the %DFS algorithm from the root node(s)
534 ///%DFS path to each node. The algorithm computes
536 ///- The distance of each node from the root(s) in the %DFS tree.
540 while ( !emptyQueue() ) processNextEdge();
543 ///Executes the algorithm until \c dest is reached.
545 ///Executes the algorithm until \c dest is reached.
547 ///\pre init() must be called and at least one node should be added
548 ///with addSource() before using this function.
550 ///This method runs the %DFS algorithm from the root node(s)
553 ///%DFS path to \c dest. The algorithm computes
554 ///- The %DFS path to \c dest.
555 ///- The distance of \c dest from the root(s) in the %DFS tree.
557 void start(Node dest)
559 while ( !emptyQueue() && G->target(_stack[_stack_head])!=dest )
563 ///Executes the algorithm until a condition is met.
565 ///Executes the algorithm until a condition is met.
567 ///\pre init() must be called and at least one node should be added
568 ///with addSource() before using this function.
570 ///\param em must be a bool (or convertible) edge map. The algorithm
571 ///will stop when it reaches an edge \c e with <tt>em[e]</tt> true.
573 ///\return The reached edge \c e with <tt>em[e]</tt> true or
574 ///\c INVALID if no such edge was found.
576 ///\warning Contrary to \ref Bfs and \ref Dijkstra, \c em is an edge map,
579 Edge start(const EM &em)
581 while ( !emptyQueue() && !em[_stack[_stack_head]] )
583 return emptyQueue() ? INVALID : _stack[_stack_head];
586 ///Runs %DFS algorithm to visit all nodes in the graph.
588 ///This method runs the %DFS algorithm in order to
590 ///%DFS path to each node. The algorithm computes
592 ///- The distance of each node from the root in the %DFS tree.
594 ///\note d.run() is just a shortcut of the following code.
597 /// for (NodeIt it(graph); it != INVALID; ++it) {
598 /// if (!d.reached(it)) {
606 for (NodeIt it(*G); it != INVALID; ++it) {
614 ///Runs %DFS algorithm from node \c s.
616 ///This method runs the %DFS algorithm from a root node \c s
619 ///%DFS path to each node. The algorithm computes
621 ///- The distance of each node from the root in the %DFS tree.
623 ///\note d.run(s) is just a shortcut of the following code.
635 ///Finds the %DFS path between \c s and \c t.
637 ///Finds the %DFS path between \c s and \c t.
639 ///\return The length of the %DFS s---t path if there exists one,
641 ///\note Apart from the return value, d.run(s,t) is
642 ///just a shortcut of the following code.
648 int run(Node s,Node t) {
652 return reached(t)?_stack_head+1:0;
657 ///\name Query Functions
658 ///The result of the %DFS algorithm can be obtained using these
660 ///Before the use of these functions,
661 ///either run() or start() must be called.
665 typedef PredMapPath<Graph, PredMap> Path;
667 ///Gives back the shortest path.
669 ///Gives back the shortest path.
670 ///\pre The \c t should be reachable from the source.
673 return Path(*G, *_pred, t);
676 ///The distance of a node from the root(s).
678 ///Returns the distance of a node from the root(s).
679 ///\pre \ref run() must be called before using this function.
680 ///\warning If node \c v is unreachable from the root(s) then the return
681 ///value of this funcion is undefined.
682 int dist(Node v) const { return (*_dist)[v]; }
684 ///Returns the 'previous edge' of the %DFS tree.
686 ///For a node \c v it returns the 'previous edge'
688 ///i.e. it returns the last edge of a %DFS path from the root(s) to \c
689 ///v. It is \ref INVALID
690 ///if \c v is unreachable from the root(s) or \c v is a root. The
691 ///%DFS tree used here is equal to the %DFS tree used in
693 ///\pre Either \ref run() or \ref start() must be called before using
695 Edge predEdge(Node v) const { return (*_pred)[v];}
697 ///Returns the 'previous node' of the %DFS tree.
699 ///For a node \c v it returns the 'previous node'
701 ///i.e. it returns the last but one node from a %DFS path from the
703 ///It is INVALID if \c v is unreachable from the root(s) or
704 ///if \c v itself a root.
705 ///The %DFS tree used here is equal to the %DFS
706 ///tree used in \ref predEdge().
707 ///\pre Either \ref run() or \ref start() must be called before
708 ///using this function.
709 Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
710 G->source((*_pred)[v]); }
712 ///Returns a reference to the NodeMap of distances.
714 ///Returns a reference to the NodeMap of distances.
715 ///\pre Either \ref run() or \ref init() must
716 ///be called before using this function.
717 const DistMap &distMap() const { return *_dist;}
719 ///Returns a reference to the %DFS edge-tree map.
721 ///Returns a reference to the NodeMap of the edges of the
723 ///\pre Either \ref run() or \ref init()
724 ///must be called before using this function.
725 const PredMap &predMap() const { return *_pred;}
727 ///Checks if a node is reachable from the root.
729 ///Returns \c true if \c v is reachable from the root(s).
730 ///\warning The source nodes are inditated as unreachable.
731 ///\pre Either \ref run() or \ref start()
732 ///must be called before using this function.
734 bool reached(Node v) { return (*_reached)[v]; }
739 ///Default traits class of Dfs function.
741 ///Default traits class of Dfs function.
742 ///\param GR Graph type.
744 struct DfsWizardDefaultTraits
746 ///The graph type the algorithm runs on.
748 ///\brief The type of the map that stores the last
749 ///edges of the %DFS paths.
751 ///The type of the map that stores the last
752 ///edges of the %DFS paths.
753 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
755 typedef NullMap<typename Graph::Node,typename GR::Edge> PredMap;
756 ///Instantiates a PredMap.
758 ///This function instantiates a \ref PredMap.
759 ///\param g is the graph, to which we would like to define the PredMap.
760 ///\todo The graph alone may be insufficient to initialize
762 static PredMap *createPredMap(const GR &g)
764 static PredMap *createPredMap(const GR &)
767 return new PredMap();
770 ///The type of the map that indicates which nodes are processed.
772 ///The type of the map that indicates which nodes are processed.
773 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
774 ///\todo named parameter to set this type, function to read and write.
775 typedef NullMap<typename Graph::Node,bool> ProcessedMap;
776 ///Instantiates a ProcessedMap.
778 ///This function instantiates a \ref ProcessedMap.
779 ///\param g is the graph, to which
780 ///we would like to define the \ref ProcessedMap
782 static ProcessedMap *createProcessedMap(const GR &g)
784 static ProcessedMap *createProcessedMap(const GR &)
787 return new ProcessedMap();
789 ///The type of the map that indicates which nodes are reached.
791 ///The type of the map that indicates which nodes are reached.
792 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
793 ///\todo named parameter to set this type, function to read and write.
794 typedef typename Graph::template NodeMap<bool> ReachedMap;
795 ///Instantiates a ReachedMap.
797 ///This function instantiates a \ref ReachedMap.
798 ///\param G is the graph, to which
799 ///we would like to define the \ref ReachedMap.
800 static ReachedMap *createReachedMap(const GR &G)
802 return new ReachedMap(G);
804 ///The type of the map that stores the dists of the nodes.
806 ///The type of the map that stores the dists of the nodes.
807 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
809 typedef NullMap<typename Graph::Node,int> DistMap;
810 ///Instantiates a DistMap.
812 ///This function instantiates a \ref DistMap.
813 ///\param g is the graph, to which we would like to define the \ref DistMap
815 static DistMap *createDistMap(const GR &g)
817 static DistMap *createDistMap(const GR &)
820 return new DistMap();
824 /// Default traits used by \ref DfsWizard
826 /// To make it easier to use Dfs algorithm
827 ///we have created a wizard class.
828 /// This \ref DfsWizard class needs default traits,
829 ///as well as the \ref Dfs class.
830 /// The \ref DfsWizardBase is a class to be the default traits of the
831 /// \ref DfsWizard class.
833 class DfsWizardBase : public DfsWizardDefaultTraits<GR>
836 typedef DfsWizardDefaultTraits<GR> Base;
838 /// Type of the nodes in the graph.
839 typedef typename Base::Graph::Node Node;
841 /// Pointer to the underlying graph.
843 ///Pointer to the map of reached nodes.
845 ///Pointer to the map of processed nodes.
847 ///Pointer to the map of predecessors edges.
849 ///Pointer to the map of distances.
851 ///Pointer to the source node.
857 /// This constructor does not require parameters, therefore it initiates
858 /// all of the attributes to default values (0, INVALID).
859 DfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0),
860 _dist(0), _source(INVALID) {}
864 /// This constructor requires some parameters,
865 /// listed in the parameters list.
866 /// Others are initiated to 0.
867 /// \param g is the initial value of \ref _g
868 /// \param s is the initial value of \ref _source
869 DfsWizardBase(const GR &g, Node s=INVALID) :
870 _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
871 _reached(0), _processed(0), _pred(0), _dist(0), _source(s) {}
875 /// A class to make the usage of the Dfs algorithm easier
877 /// This class is created to make it easier to use the Dfs algorithm.
878 /// It uses the functions and features of the plain \ref Dfs,
879 /// but it is much simpler to use it.
881 /// Simplicity means that the way to change the types defined
882 /// in the traits class is based on functions that returns the new class
883 /// and not on templatable built-in classes.
884 /// When using the plain \ref Dfs
885 /// the new class with the modified type comes from
886 /// the original class by using the ::
887 /// operator. In the case of \ref DfsWizard only
888 /// a function have to be called and it will
889 /// return the needed class.
891 /// It does not have own \ref run method. When its \ref run method is called
892 /// it initiates a plain \ref Dfs object, and calls the \ref Dfs::run
895 class DfsWizard : public TR
899 ///The type of the underlying graph.
900 typedef typename TR::Graph Graph;
902 typedef typename Graph::Node Node;
904 typedef typename Graph::NodeIt NodeIt;
906 typedef typename Graph::Edge Edge;
908 typedef typename Graph::OutEdgeIt OutEdgeIt;
910 ///\brief The type of the map that stores
912 typedef typename TR::ReachedMap ReachedMap;
913 ///\brief The type of the map that stores
914 ///the processed nodes
915 typedef typename TR::ProcessedMap ProcessedMap;
916 ///\brief The type of the map that stores the last
917 ///edges of the %DFS paths.
918 typedef typename TR::PredMap PredMap;
919 ///The type of the map that stores the distances of the nodes.
920 typedef typename TR::DistMap DistMap;
924 DfsWizard() : TR() {}
926 /// Constructor that requires parameters.
928 /// Constructor that requires parameters.
929 /// These parameters will be the default values for the traits class.
930 DfsWizard(const Graph &g, Node s=INVALID) :
934 DfsWizard(const TR &b) : TR(b) {}
938 ///Runs Dfs algorithm from a given node.
940 ///Runs Dfs algorithm from a given node.
941 ///The node can be given by the \ref source function.
944 if(Base::_source==INVALID) throw UninitializedParameter();
945 Dfs<Graph,TR> alg(*reinterpret_cast<const Graph*>(Base::_g));
947 alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
949 alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
951 alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
953 alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
954 alg.run(Base::_source);
957 ///Runs Dfs algorithm from the given node.
959 ///Runs Dfs algorithm from the given node.
960 ///\param s is the given source.
968 struct DefPredMapBase : public Base {
970 static PredMap *createPredMap(const Graph &) { return 0; };
971 DefPredMapBase(const TR &b) : TR(b) {}
974 ///\brief \ref named-templ-param "Named parameter"
975 ///function for setting PredMap type
977 /// \ref named-templ-param "Named parameter"
978 ///function for setting PredMap type
981 DfsWizard<DefPredMapBase<T> > predMap(const T &t)
983 Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
984 return DfsWizard<DefPredMapBase<T> >(*this);
989 struct DefReachedMapBase : public Base {
990 typedef T ReachedMap;
991 static ReachedMap *createReachedMap(const Graph &) { return 0; };
992 DefReachedMapBase(const TR &b) : TR(b) {}
995 ///\brief \ref named-templ-param "Named parameter"
996 ///function for setting ReachedMap
998 /// \ref named-templ-param "Named parameter"
999 ///function for setting ReachedMap
1002 DfsWizard<DefReachedMapBase<T> > reachedMap(const T &t)
1004 Base::_reached=reinterpret_cast<void*>(const_cast<T*>(&t));
1005 return DfsWizard<DefReachedMapBase<T> >(*this);
1010 struct DefProcessedMapBase : public Base {
1011 typedef T ProcessedMap;
1012 static ProcessedMap *createProcessedMap(const Graph &) { return 0; };
1013 DefProcessedMapBase(const TR &b) : TR(b) {}
1016 ///\brief \ref named-templ-param "Named parameter"
1017 ///function for setting ProcessedMap
1019 /// \ref named-templ-param "Named parameter"
1020 ///function for setting ProcessedMap
1023 DfsWizard<DefProcessedMapBase<T> > processedMap(const T &t)
1025 Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1026 return DfsWizard<DefProcessedMapBase<T> >(*this);
1030 struct DefDistMapBase : public Base {
1032 static DistMap *createDistMap(const Graph &) { return 0; };
1033 DefDistMapBase(const TR &b) : TR(b) {}
1036 ///\brief \ref named-templ-param "Named parameter"
1037 ///function for setting DistMap type
1039 /// \ref named-templ-param "Named parameter"
1040 ///function for setting DistMap type
1043 DfsWizard<DefDistMapBase<T> > distMap(const T &t)
1045 Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1046 return DfsWizard<DefDistMapBase<T> >(*this);
1049 /// Sets the source node, from which the Dfs algorithm runs.
1051 /// Sets the source node, from which the Dfs algorithm runs.
1052 /// \param s is the source node.
1053 DfsWizard<TR> &source(Node s)
1061 ///Function type interface for Dfs algorithm.
1064 ///Function type interface for Dfs algorithm.
1066 ///This function also has several
1067 ///\ref named-templ-func-param "named parameters",
1068 ///they are declared as the members of class \ref DfsWizard.
1070 ///example shows how to use these parameters.
1072 /// dfs(g,source).predMap(preds).run();
1074 ///\warning Don't forget to put the \ref DfsWizard::run() "run()"
1075 ///to the end of the parameter list.
1079 DfsWizard<DfsWizardBase<GR> >
1080 dfs(const GR &g,typename GR::Node s=INVALID)
1082 return DfsWizard<DfsWizardBase<GR> >(g,s);
1086 /// \brief Visitor class for dfs.
1088 /// It gives a simple interface for a functional interface for dfs
1089 /// traversal. The traversal on a linear data structure.
1090 template <typename _Graph>
1092 typedef _Graph Graph;
1093 typedef typename Graph::Edge Edge;
1094 typedef typename Graph::Node Node;
1095 /// \brief Called when the edge reach a node.
1097 /// It is called when the dfs find an edge which target is not
1099 void discover(const Edge& edge) {}
1100 /// \brief Called when the node reached first time.
1102 /// It is Called when the node reached first time.
1103 void reach(const Node& node) {}
1104 /// \brief Called when we step back on an edge.
1106 /// It is called when the dfs should step back on the edge.
1107 void backtrack(const Edge& edge) {}
1108 /// \brief Called when we step back from the node.
1110 /// It is called when we step back from the node.
1111 void leave(const Node& node) {}
1112 /// \brief Called when the edge examined but target of the edge
1113 /// already discovered.
1115 /// It called when the edge examined but the target of the edge
1116 /// already discovered.
1117 void examine(const Edge& edge) {}
1118 /// \brief Called for the source node of the dfs.
1120 /// It is called for the source node of the dfs.
1121 void start(const Node& node) {}
1122 /// \brief Called when we leave the source node of the dfs.
1124 /// It is called when we leave the source node of the dfs.
1125 void stop(const Node& node) {}
1129 template <typename _Graph>
1131 typedef _Graph Graph;
1132 typedef typename Graph::Edge Edge;
1133 typedef typename Graph::Node Node;
1134 void discover(const Edge&) {}
1135 void reach(const Node&) {}
1136 void backtrack(const Edge&) {}
1137 void leave(const Node&) {}
1138 void examine(const Edge&) {}
1139 void start(const Node&) {}
1140 void stop(const Node&) {}
1142 template <typename _Visitor>
1143 struct Constraints {
1144 void constraints() {
1147 visitor.discover(edge);
1148 visitor.reach(node);
1149 visitor.backtrack(edge);
1150 visitor.leave(node);
1151 visitor.examine(edge);
1152 visitor.start(node);
1160 /// \brief Default traits class of DfsVisit class.
1162 /// Default traits class of DfsVisit class.
1163 /// \param _Graph Graph type.
1164 template<class _Graph>
1165 struct DfsVisitDefaultTraits {
1167 /// \brief The graph type the algorithm runs on.
1168 typedef _Graph Graph;
1170 /// \brief The type of the map that indicates which nodes are reached.
1172 /// The type of the map that indicates which nodes are reached.
1173 /// It must meet the \ref concepts::WriteMap "WriteMap" concept.
1174 /// \todo named parameter to set this type, function to read and write.
1175 typedef typename Graph::template NodeMap<bool> ReachedMap;
1177 /// \brief Instantiates a ReachedMap.
1179 /// This function instantiates a \ref ReachedMap.
1180 /// \param graph is the graph, to which
1181 /// we would like to define the \ref ReachedMap.
1182 static ReachedMap *createReachedMap(const Graph &graph) {
1183 return new ReachedMap(graph);
1188 /// %DFS Visit algorithm class.
1191 /// This class provides an efficient implementation of the %DFS algorithm
1192 /// with visitor interface.
1194 /// The %DfsVisit class provides an alternative interface to the Dfs
1195 /// class. It works with callback mechanism, the DfsVisit object calls
1196 /// on every dfs event the \c Visitor class member functions.
1198 /// \param _Graph The graph type the algorithm runs on. The default value is
1199 /// \ref ListGraph. The value of _Graph is not used directly by Dfs, it
1200 /// is only passed to \ref DfsDefaultTraits.
1201 /// \param _Visitor The Visitor object for the algorithm. The
1202 /// \ref DfsVisitor "DfsVisitor<_Graph>" is an empty Visitor which
1203 /// does not observe the Dfs events. If you want to observe the dfs
1204 /// events you should implement your own Visitor class.
1205 /// \param _Traits Traits class to set various data types used by the
1206 /// algorithm. The default traits class is
1207 /// \ref DfsVisitDefaultTraits "DfsVisitDefaultTraits<_Graph>".
1208 /// See \ref DfsVisitDefaultTraits for the documentation of
1209 /// a Dfs visit traits class.
1211 /// \author Jacint Szabo, Alpar Juttner and Balazs Dezso
1213 template <typename _Graph, typename _Visitor, typename _Traits>
1215 template <typename _Graph = ListGraph,
1216 typename _Visitor = DfsVisitor<_Graph>,
1217 typename _Traits = DfsDefaultTraits<_Graph> >
1222 /// \brief \ref Exception for uninitialized parameters.
1224 /// This error represents problems in the initialization
1225 /// of the parameters of the algorithms.
1226 class UninitializedParameter : public lemon::UninitializedParameter {
1228 virtual const char* what() const throw()
1230 return "lemon::DfsVisit::UninitializedParameter";
1234 typedef _Traits Traits;
1236 typedef typename Traits::Graph Graph;
1238 typedef _Visitor Visitor;
1240 ///The type of the map indicating which nodes are reached.
1241 typedef typename Traits::ReachedMap ReachedMap;
1245 typedef typename Graph::Node Node;
1246 typedef typename Graph::NodeIt NodeIt;
1247 typedef typename Graph::Edge Edge;
1248 typedef typename Graph::OutEdgeIt OutEdgeIt;
1250 /// Pointer to the underlying graph.
1251 const Graph *_graph;
1252 /// Pointer to the visitor object.
1254 ///Pointer to the map of reached status of the nodes.
1255 ReachedMap *_reached;
1256 ///Indicates if \ref _reached is locally allocated (\c true) or not.
1259 std::vector<typename Graph::Edge> _stack;
1262 /// \brief Creates the maps if necessary.
1264 /// Creates the maps if necessary.
1265 void create_maps() {
1267 local_reached = true;
1268 _reached = Traits::createReachedMap(*_graph);
1278 typedef DfsVisit Create;
1280 /// \name Named template parameters
1284 struct DefReachedMapTraits : public Traits {
1285 typedef T ReachedMap;
1286 static ReachedMap *createReachedMap(const Graph &graph) {
1287 throw UninitializedParameter();
1290 /// \brief \ref named-templ-param "Named parameter" for setting
1293 /// \ref named-templ-param "Named parameter" for setting ReachedMap type
1295 struct DefReachedMap : public DfsVisit< Graph, Visitor,
1296 DefReachedMapTraits<T> > {
1297 typedef DfsVisit< Graph, Visitor, DefReachedMapTraits<T> > Create;
1303 /// \brief Constructor.
1307 /// \param graph the graph the algorithm will run on.
1308 /// \param visitor The visitor of the algorithm.
1310 DfsVisit(const Graph& graph, Visitor& visitor)
1311 : _graph(&graph), _visitor(&visitor),
1312 _reached(0), local_reached(false) {}
1314 /// \brief Destructor.
1318 if(local_reached) delete _reached;
1321 /// \brief Sets the map indicating if a node is reached.
1323 /// Sets the map indicating if a node is reached.
1324 /// If you don't use this function before calling \ref run(),
1325 /// it will allocate one. The destuctor deallocates this
1326 /// automatically allocated map, of course.
1327 /// \return <tt> (*this) </tt>
1328 DfsVisit &reachedMap(ReachedMap &m) {
1331 local_reached=false;
1338 /// \name Execution control
1339 /// The simplest way to execute the algorithm is to use
1340 /// one of the member functions called \c run(...).
1342 /// If you need more control on the execution,
1343 /// first you must call \ref init(), then you can adda source node
1344 /// with \ref addSource().
1345 /// Finally \ref start() will perform the actual path
1349 /// \brief Initializes the internal data structures.
1351 /// Initializes the internal data structures.
1355 _stack.resize(countNodes(*_graph));
1357 for (NodeIt u(*_graph) ; u != INVALID ; ++u) {
1358 _reached->set(u, false);
1362 /// \brief Adds a new source node.
1364 /// Adds a new source node to the set of nodes to be processed.
1365 void addSource(Node s) {
1366 if(!(*_reached)[s]) {
1367 _reached->set(s,true);
1371 _graph->firstOut(e, s);
1373 _stack[++_stack_head] = e;
1380 /// \brief Processes the next edge.
1382 /// Processes the next edge.
1384 /// \return The processed edge.
1386 /// \pre The stack must not be empty!
1387 Edge processNextEdge() {
1388 Edge e = _stack[_stack_head];
1389 Node m = _graph->target(e);
1390 if(!(*_reached)[m]) {
1391 _visitor->discover(e);
1393 _reached->set(m, true);
1394 _graph->firstOut(_stack[++_stack_head], m);
1396 _visitor->examine(e);
1397 m = _graph->source(e);
1398 _graph->nextOut(_stack[_stack_head]);
1400 while (_stack_head>=0 && _stack[_stack_head] == INVALID) {
1403 if (_stack_head >= 0) {
1404 _visitor->backtrack(_stack[_stack_head]);
1405 m = _graph->source(_stack[_stack_head]);
1406 _graph->nextOut(_stack[_stack_head]);
1414 /// \brief Next edge to be processed.
1416 /// Next edge to be processed.
1418 /// \return The next edge to be processed or INVALID if the stack is
1421 return _stack_head >= 0 ? _stack[_stack_head] : INVALID;
1424 /// \brief Returns \c false if there are nodes
1425 /// to be processed in the queue
1427 /// Returns \c false if there are nodes
1428 /// to be processed in the queue
1429 bool emptyQueue() { return _stack_head < 0; }
1431 /// \brief Returns the number of the nodes to be processed.
1433 /// Returns the number of the nodes to be processed in the queue.
1434 int queueSize() { return _stack_head + 1; }
1436 /// \brief Executes the algorithm.
1438 /// Executes the algorithm.
1440 /// \pre init() must be called and at least one node should be added
1441 /// with addSource() before using this function.
1443 while ( !emptyQueue() ) processNextEdge();
1446 /// \brief Executes the algorithm until \c dest is reached.
1448 /// Executes the algorithm until \c dest is reached.
1450 /// \pre init() must be called and at least one node should be added
1451 /// with addSource() before using this function.
1452 void start(Node dest) {
1453 while ( !emptyQueue() && _graph->target(_stack[_stack_head]) != dest )
1457 /// \brief Executes the algorithm until a condition is met.
1459 /// Executes the algorithm until a condition is met.
1461 /// \pre init() must be called and at least one node should be added
1462 /// with addSource() before using this function.
1464 /// \param em must be a bool (or convertible) edge map. The algorithm
1465 /// will stop when it reaches an edge \c e with <tt>em[e]</tt> true.
1467 ///\return The reached edge \c e with <tt>em[e]</tt> true or
1468 ///\c INVALID if no such edge was found.
1470 /// \warning Contrary to \ref Bfs and \ref Dijkstra, \c em is an edge map,
1472 template <typename EM>
1473 Edge start(const EM &em) {
1474 while ( !emptyQueue() && !em[_stack[_stack_head]] )
1476 return emptyQueue() ? INVALID : _stack[_stack_head];
1479 /// \brief Runs %DFSVisit algorithm from node \c s.
1481 /// This method runs the %DFS algorithm from a root node \c s.
1482 /// \note d.run(s) is just a shortcut of the following code.
1494 /// \brief Runs %DFSVisit algorithm to visit all nodes in the graph.
1496 /// This method runs the %DFS algorithm in order to
1497 /// compute the %DFS path to each node. The algorithm computes
1498 /// - The %DFS tree.
1499 /// - The distance of each node from the root in the %DFS tree.
1501 ///\note d.run() is just a shortcut of the following code.
1504 /// for (NodeIt it(graph); it != INVALID; ++it) {
1505 /// if (!d.reached(it)) {
1506 /// d.addSource(it);
1513 for (NodeIt it(*_graph); it != INVALID; ++it) {
1522 /// \name Query Functions
1523 /// The result of the %DFS algorithm can be obtained using these
1525 /// Before the use of these functions,
1526 /// either run() or start() must be called.
1528 /// \brief Checks if a node is reachable from the root.
1530 /// Returns \c true if \c v is reachable from the root(s).
1531 /// \warning The source nodes are inditated as unreachable.
1532 /// \pre Either \ref run() or \ref start()
1533 /// must be called before using this function.
1535 bool reached(Node v) { return (*_reached)[v]; }
1540 } //END OF NAMESPACE LEMON