1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
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/bits/path_dump.h>
28 #include <lemon/core.h>
29 #include <lemon/error.h>
30 #include <lemon/assert.h>
31 #include <lemon/maps.h>
35 ///Default traits class of Dfs class.
37 ///Default traits class of Dfs class.
38 ///\tparam GR Digraph type.
40 struct DfsDefaultTraits
42 ///The type of the digraph the algorithm runs on.
45 ///\brief The type of the map that stores the predecessor
46 ///arcs of the %DFS paths.
48 ///The type of the map that stores the predecessor
49 ///arcs of the %DFS paths.
50 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
51 typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
52 ///Instantiates a \ref PredMap.
54 ///This function instantiates a \ref PredMap.
55 ///\param g is the digraph, to which we would like to define the
57 ///\todo The digraph alone may be insufficient to initialize
58 static PredMap *createPredMap(const Digraph &g)
60 return new PredMap(g);
63 ///The type of the map that indicates which nodes are processed.
65 ///The type of the map that indicates which nodes are processed.
66 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
67 ///By default it is a NullMap.
68 typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
69 ///Instantiates a \ref ProcessedMap.
71 ///This function instantiates a \ref ProcessedMap.
72 ///\param g is the digraph, to which
73 ///we would like to define the \ref ProcessedMap
75 static ProcessedMap *createProcessedMap(const Digraph &g)
77 static ProcessedMap *createProcessedMap(const Digraph &)
80 return new ProcessedMap();
83 ///The type of the map that indicates which nodes are reached.
85 ///The type of the map that indicates which nodes are reached.
86 ///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
87 typedef typename Digraph::template NodeMap<bool> ReachedMap;
88 ///Instantiates a \ref ReachedMap.
90 ///This function instantiates a \ref ReachedMap.
91 ///\param g is the digraph, to which
92 ///we would like to define the \ref ReachedMap.
93 static ReachedMap *createReachedMap(const Digraph &g)
95 return new ReachedMap(g);
98 ///The type of the map that stores the distances of the nodes.
100 ///The type of the map that stores the distances of the nodes.
101 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
102 typedef typename Digraph::template NodeMap<int> DistMap;
103 ///Instantiates a \ref DistMap.
105 ///This function instantiates a \ref DistMap.
106 ///\param g is the digraph, to which we would like to define the
108 static DistMap *createDistMap(const Digraph &g)
110 return new DistMap(g);
114 ///%DFS algorithm class.
117 ///This class provides an efficient implementation of the %DFS algorithm.
119 ///There is also a \ref dfs() "function type interface" for the DFS
120 ///algorithm, which is convenient in the simplier cases and it can be
123 ///\tparam GR The type of the digraph the algorithm runs on.
124 ///The default value is \ref ListDigraph. The value of GR is not used
125 ///directly by \ref Dfs, it is only passed to \ref DfsDefaultTraits.
126 ///\tparam TR Traits class to set various data types used by the algorithm.
127 ///The default traits class is
128 ///\ref DfsDefaultTraits "DfsDefaultTraits<GR>".
129 ///See \ref DfsDefaultTraits for the documentation of
130 ///a Dfs traits class.
132 template <typename GR,
135 template <typename GR=ListDigraph,
136 typename TR=DfsDefaultTraits<GR> >
140 ///\ref Exception for uninitialized parameters.
142 ///This error represents problems in the initialization of the
143 ///parameters of the algorithm.
144 class UninitializedParameter : public lemon::UninitializedParameter {
146 virtual const char* what() const throw() {
147 return "lemon::Dfs::UninitializedParameter";
151 ///The type of the digraph the algorithm runs on.
152 typedef typename TR::Digraph Digraph;
154 ///\brief The type of the map that stores the predecessor arcs of the
156 typedef typename TR::PredMap PredMap;
157 ///The type of the map that stores the distances of the nodes.
158 typedef typename TR::DistMap DistMap;
159 ///The type of the map that indicates which nodes are reached.
160 typedef typename TR::ReachedMap ReachedMap;
161 ///The type of the map that indicates which nodes are processed.
162 typedef typename TR::ProcessedMap ProcessedMap;
163 ///The type of the paths.
164 typedef PredMapPath<Digraph, PredMap> Path;
171 typedef typename Digraph::Node Node;
172 typedef typename Digraph::NodeIt NodeIt;
173 typedef typename Digraph::Arc Arc;
174 typedef typename Digraph::OutArcIt OutArcIt;
176 //Pointer to the underlying digraph.
178 //Pointer to the map of predecessor arcs.
180 //Indicates if _pred is locally allocated (true) or not.
182 //Pointer to the map of distances.
184 //Indicates if _dist is locally allocated (true) or not.
186 //Pointer to the map of reached status of the nodes.
187 ReachedMap *_reached;
188 //Indicates if _reached is locally allocated (true) or not.
190 //Pointer to the map of processed status of the nodes.
191 ProcessedMap *_processed;
192 //Indicates if _processed is locally allocated (true) or not.
193 bool local_processed;
195 std::vector<typename Digraph::OutArcIt> _stack;
198 ///Creates the maps if necessary.
199 ///\todo Better memory allocation (instead of new).
204 _pred = Traits::createPredMap(*G);
208 _dist = Traits::createDistMap(*G);
211 local_reached = true;
212 _reached = Traits::createReachedMap(*G);
215 local_processed = true;
216 _processed = Traits::createProcessedMap(*G);
228 ///\name Named template parameters
233 struct DefPredMapTraits : public Traits {
235 static PredMap *createPredMap(const Digraph &)
237 throw UninitializedParameter();
240 ///\brief \ref named-templ-param "Named parameter" for setting
241 ///\ref PredMap type.
243 ///\ref named-templ-param "Named parameter" for setting
244 ///\ref PredMap type.
246 struct DefPredMap : public Dfs<Digraph, DefPredMapTraits<T> > {
247 typedef Dfs<Digraph, DefPredMapTraits<T> > Create;
251 struct DefDistMapTraits : public Traits {
253 static DistMap *createDistMap(const Digraph &)
255 throw UninitializedParameter();
258 ///\brief \ref named-templ-param "Named parameter" for setting
259 ///\ref DistMap type.
261 ///\ref named-templ-param "Named parameter" for setting
262 ///\ref DistMap type.
264 struct DefDistMap : public Dfs< Digraph, DefDistMapTraits<T> > {
265 typedef Dfs<Digraph, DefDistMapTraits<T> > Create;
269 struct DefReachedMapTraits : public Traits {
270 typedef T ReachedMap;
271 static ReachedMap *createReachedMap(const Digraph &)
273 throw UninitializedParameter();
276 ///\brief \ref named-templ-param "Named parameter" for setting
277 ///\ref ReachedMap type.
279 ///\ref named-templ-param "Named parameter" for setting
280 ///\ref ReachedMap type.
282 struct DefReachedMap : public Dfs< Digraph, DefReachedMapTraits<T> > {
283 typedef Dfs< Digraph, DefReachedMapTraits<T> > Create;
287 struct DefProcessedMapTraits : public Traits {
288 typedef T ProcessedMap;
289 static ProcessedMap *createProcessedMap(const Digraph &)
291 throw UninitializedParameter();
294 ///\brief \ref named-templ-param "Named parameter" for setting
295 ///\ref ProcessedMap type.
297 ///\ref named-templ-param "Named parameter" for setting
298 ///\ref ProcessedMap type.
300 struct DefProcessedMap : public Dfs< Digraph, DefProcessedMapTraits<T> > {
301 typedef Dfs< Digraph, DefProcessedMapTraits<T> > Create;
304 struct DefDigraphProcessedMapTraits : public Traits {
305 typedef typename Digraph::template NodeMap<bool> ProcessedMap;
306 static ProcessedMap *createProcessedMap(const Digraph &g)
308 return new ProcessedMap(g);
311 ///\brief \ref named-templ-param "Named parameter" for setting
312 ///\ref ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
314 ///\ref named-templ-param "Named parameter" for setting
315 ///\ref ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
316 ///If you don't set it explicitly, it will be automatically allocated.
318 struct DefProcessedMapToBeDefaultMap :
319 public Dfs< Digraph, DefDigraphProcessedMapTraits> {
320 typedef Dfs< Digraph, DefDigraphProcessedMapTraits> Create;
330 ///\param g The digraph the algorithm runs on.
331 Dfs(const Digraph &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 that stores the predecessor arcs.
350 ///Sets the map that stores the predecessor arcs.
351 ///If you don't use this function before calling \ref run(),
352 ///it will allocate one. The destructor deallocates this
353 ///automatically allocated map, of course.
354 ///\return <tt> (*this) </tt>
355 Dfs &predMap(PredMap &m)
365 ///Sets the map that indicates which nodes are reached.
367 ///Sets the map that indicates which nodes are reached.
368 ///If you don't use this function before calling \ref run(),
369 ///it will allocate one. The destructor deallocates this
370 ///automatically allocated map, of course.
371 ///\return <tt> (*this) </tt>
372 Dfs &reachedMap(ReachedMap &m)
382 ///Sets the map that indicates which nodes are processed.
384 ///Sets the map that indicates which nodes are processed.
385 ///If you don't use this function before calling \ref run(),
386 ///it will allocate one. The destructor deallocates this
387 ///automatically allocated map, of course.
388 ///\return <tt> (*this) </tt>
389 Dfs &processedMap(ProcessedMap &m)
391 if(local_processed) {
393 local_processed=false;
399 ///Sets the map that stores the distances of the nodes.
401 ///Sets the map that stores the distances of the nodes calculated by
403 ///If you don't use this function before calling \ref run(),
404 ///it will allocate one. The destructor deallocates this
405 ///automatically allocated map, of course.
406 ///\return <tt> (*this) </tt>
407 Dfs &distMap(DistMap &m)
419 ///\name Execution control
420 ///The simplest way to execute the algorithm is to use
421 ///one of the member functions called \ref lemon::Dfs::run() "run()".
423 ///If you need more control on the execution, first you must call
424 ///\ref lemon::Dfs::init() "init()", then you can add a source node
425 ///with \ref lemon::Dfs::addSource() "addSource()".
426 ///Finally \ref lemon::Dfs::start() "start()" will perform the
427 ///actual path computation.
431 ///Initializes the internal data structures.
433 ///Initializes the internal data structures.
438 _stack.resize(countNodes(*G));
440 for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
441 _pred->set(u,INVALID);
442 _reached->set(u,false);
443 _processed->set(u,false);
447 ///Adds a new source node.
449 ///Adds a new source node to the set of nodes to be processed.
451 ///\pre The stack must be empty. (Otherwise the algorithm gives
454 ///\warning Distances will be wrong (or at least strange) in case of
456 void addSource(Node s)
458 LEMON_DEBUG(emptyQueue(), "The stack is not empty.");
461 _reached->set(s,true);
462 _pred->set(s,INVALID);
465 _stack[++_stack_head]=e;
466 _dist->set(s,_stack_head);
469 _processed->set(s,true);
475 ///Processes the next arc.
477 ///Processes the next arc.
479 ///\return The processed arc.
481 ///\pre The stack must not be empty.
485 Arc e=_stack[_stack_head];
486 if(!(*_reached)[m=G->target(e)]) {
488 _reached->set(m,true);
490 _stack[_stack_head] = OutArcIt(*G, m);
491 _dist->set(m,_stack_head);
495 ++_stack[_stack_head];
497 while(_stack_head>=0 && _stack[_stack_head]==INVALID) {
498 _processed->set(m,true);
501 m=G->source(_stack[_stack_head]);
502 ++_stack[_stack_head];
508 ///Next arc to be processed.
510 ///Next arc to be processed.
512 ///\return The next arc to be processed or \c INVALID if the stack
514 OutArcIt nextArc() const
516 return _stack_head>=0?_stack[_stack_head]:INVALID;
519 ///\brief Returns \c false if there are nodes
522 ///Returns \c false if there are nodes
523 ///to be processed in the queue (stack).
524 bool emptyQueue() const { return _stack_head<0; }
526 ///Returns the number of the nodes to be processed.
528 ///Returns the number of the nodes to be processed in the queue (stack).
529 int queueSize() const { return _stack_head+1; }
531 ///Executes the algorithm.
533 ///Executes the algorithm.
535 ///This method runs the %DFS algorithm from the root node
536 ///in order to compute the DFS path to each node.
538 /// The algorithm computes
540 ///- the distance of each node from the root in the %DFS tree.
542 ///\pre init() must be called and a root node should be
543 ///added with addSource() before using this function.
545 ///\note <tt>d.start()</tt> is just a shortcut of the following code.
547 /// while ( !d.emptyQueue() ) {
548 /// d.processNextArc();
553 while ( !emptyQueue() ) processNextArc();
556 ///Executes the algorithm until the given target node is reached.
558 ///Executes the algorithm until the given target node is reached.
560 ///This method runs the %DFS algorithm from the root node
561 ///in order to compute the DFS path to \c dest.
563 ///The algorithm computes
564 ///- the %DFS path to \c dest,
565 ///- the distance of \c dest from the root in the %DFS tree.
567 ///\pre init() must be called and a root node should be
568 ///added with addSource() before using this function.
569 void start(Node dest)
571 while ( !emptyQueue() && G->target(_stack[_stack_head])!=dest )
575 ///Executes the algorithm until a condition is met.
577 ///Executes the algorithm until a condition is met.
579 ///This method runs the %DFS algorithm from the root node
580 ///until an arc \c a with <tt>am[a]</tt> true is found.
582 ///\param am A \c bool (or convertible) arc map. The algorithm
583 ///will stop when it reaches an arc \c a with <tt>am[a]</tt> true.
585 ///\return The reached arc \c a with <tt>am[a]</tt> true or
586 ///\c INVALID if no such arc was found.
588 ///\pre init() must be called and a root node should be
589 ///added with addSource() before using this function.
591 ///\warning Contrary to \ref Bfs and \ref Dijkstra, \c am is an arc map,
593 template<class ArcBoolMap>
594 Arc start(const ArcBoolMap &am)
596 while ( !emptyQueue() && !am[_stack[_stack_head]] )
598 return emptyQueue() ? INVALID : _stack[_stack_head];
601 ///Runs the algorithm from the given node.
603 ///This method runs the %DFS algorithm from node \c s
604 ///in order to compute the DFS path to each node.
606 ///The algorithm computes
608 ///- the distance of each node from the root in the %DFS tree.
610 ///\note <tt>d.run(s)</tt> is just a shortcut of the following code.
622 ///Finds the %DFS path between \c s and \c t.
624 ///This method runs the %DFS algorithm from node \c s
625 ///in order to compute the DFS path to \c t.
627 ///\return The length of the <tt>s</tt>--<tt>t</tt> DFS path,
628 ///if \c t is reachable form \c s, \c 0 otherwise.
630 ///\note Apart from the return value, <tt>d.run(s,t)</tt> is
631 ///just a shortcut of the following code.
637 int run(Node s,Node t) {
641 return reached(t)?_stack_head+1:0;
644 ///Runs the algorithm to visit all nodes in the digraph.
646 ///This method runs the %DFS algorithm in order to compute the
647 ///%DFS path to each node.
649 ///The algorithm computes
651 ///- the distance of each node from the root in the %DFS tree.
653 ///\note <tt>d.run()</tt> is just a shortcut of the following code.
656 /// for (NodeIt n(digraph); n != INVALID; ++n) {
657 /// if (!d.reached(n)) {
665 for (NodeIt it(*G); it != INVALID; ++it) {
675 ///\name Query Functions
676 ///The result of the %DFS algorithm can be obtained using these
678 ///Either \ref lemon::Dfs::run() "run()" or \ref lemon::Dfs::start()
679 ///"start()" must be called before using them.
683 ///The DFS path to a node.
685 ///Returns the DFS path to a node.
687 ///\warning \c t should be reachable from the root.
689 ///\pre Either \ref run() or \ref start() must be called before
690 ///using this function.
691 Path path(Node t) const { return Path(*G, *_pred, t); }
693 ///The distance of a node from the root.
695 ///Returns the distance of a node from the root.
697 ///\warning If node \c v is not reachable from the root, then
698 ///the return value of this function is undefined.
700 ///\pre Either \ref run() or \ref start() must be called before
701 ///using this function.
702 int dist(Node v) const { return (*_dist)[v]; }
704 ///Returns the 'previous arc' of the %DFS tree for a node.
706 ///This function returns the 'previous arc' of the %DFS tree for the
707 ///node \c v, i.e. it returns the last arc of a %DFS path from the
708 ///root to \c v. It is \c INVALID
709 ///if \c v is not reachable from the root(s) or if \c v is a root.
711 ///The %DFS tree used here is equal to the %DFS tree used in
714 ///\pre Either \ref run() or \ref start() must be called before using
716 Arc predArc(Node v) const { return (*_pred)[v];}
718 ///Returns the 'previous node' of the %DFS tree.
720 ///This function returns the 'previous node' of the %DFS
721 ///tree for the node \c v, i.e. it returns the last but one node
722 ///from a %DFS path from the root to \c v. It is \c INVALID
723 ///if \c v is not reachable from the root(s) or if \c v is a root.
725 ///The %DFS tree used here is equal to the %DFS tree used in
728 ///\pre Either \ref run() or \ref start() must be called before
729 ///using this function.
730 Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
731 G->source((*_pred)[v]); }
733 ///\brief Returns a const reference to the node map that stores the
734 ///distances of the nodes.
736 ///Returns a const reference to the node map that stores the
737 ///distances of the nodes calculated by the algorithm.
739 ///\pre Either \ref run() or \ref init()
740 ///must be called before using this function.
741 const DistMap &distMap() const { return *_dist;}
743 ///\brief Returns a const reference to the node map that stores the
746 ///Returns a const reference to the node map that stores the predecessor
747 ///arcs, which form the DFS tree.
749 ///\pre Either \ref run() or \ref init()
750 ///must be called before using this function.
751 const PredMap &predMap() const { return *_pred;}
753 ///Checks if a node is reachable from the root(s).
755 ///Returns \c true if \c v is reachable from the root(s).
756 ///\pre Either \ref run() or \ref start()
757 ///must be called before using this function.
758 bool reached(Node v) const { return (*_reached)[v]; }
763 ///Default traits class of dfs() function.
765 ///Default traits class of dfs() function.
766 ///\tparam GR Digraph type.
768 struct DfsWizardDefaultTraits
770 ///The type of the digraph the algorithm runs on.
773 ///\brief The type of the map that stores the predecessor
774 ///arcs of the %DFS paths.
776 ///The type of the map that stores the predecessor
777 ///arcs of the %DFS paths.
778 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
780 typedef NullMap<typename Digraph::Node,typename Digraph::Arc> PredMap;
781 ///Instantiates a \ref PredMap.
783 ///This function instantiates a \ref PredMap.
784 ///\param g is the digraph, to which we would like to define the
786 ///\todo The digraph alone may be insufficient to initialize
788 static PredMap *createPredMap(const Digraph &g)
790 static PredMap *createPredMap(const Digraph &)
793 return new PredMap();
796 ///The type of the map that indicates which nodes are processed.
798 ///The type of the map that indicates which nodes are processed.
799 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
800 typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
801 ///Instantiates a \ref ProcessedMap.
803 ///This function instantiates a \ref ProcessedMap.
804 ///\param g is the digraph, to which
805 ///we would like to define the \ref ProcessedMap.
807 static ProcessedMap *createProcessedMap(const Digraph &g)
809 static ProcessedMap *createProcessedMap(const Digraph &)
812 return new ProcessedMap();
815 ///The type of the map that indicates which nodes are reached.
817 ///The type of the map that indicates which nodes are reached.
818 ///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
819 typedef typename Digraph::template NodeMap<bool> ReachedMap;
820 ///Instantiates a \ref ReachedMap.
822 ///This function instantiates a \ref ReachedMap.
823 ///\param g is the digraph, to which
824 ///we would like to define the \ref ReachedMap.
825 static ReachedMap *createReachedMap(const Digraph &g)
827 return new ReachedMap(g);
830 ///The type of the map that stores the distances of the nodes.
832 ///The type of the map that stores the distances of the nodes.
833 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
835 typedef NullMap<typename Digraph::Node,int> DistMap;
836 ///Instantiates a \ref DistMap.
838 ///This function instantiates a \ref DistMap.
839 ///\param g is the digraph, to which we would like to define
842 static DistMap *createDistMap(const Digraph &g)
844 static DistMap *createDistMap(const Digraph &)
847 return new DistMap();
851 /// Default traits class used by \ref DfsWizard
853 /// To make it easier to use Dfs algorithm
854 /// we have created a wizard class.
855 /// This \ref DfsWizard class needs default traits,
856 /// as well as the \ref Dfs class.
857 /// The \ref DfsWizardBase is a class to be the default traits of the
858 /// \ref DfsWizard class.
860 class DfsWizardBase : public DfsWizardDefaultTraits<GR>
863 typedef DfsWizardDefaultTraits<GR> Base;
865 //The type of the nodes in the digraph.
866 typedef typename Base::Digraph::Node Node;
868 //Pointer to the digraph the algorithm runs on.
870 //Pointer to the map of reached nodes.
872 //Pointer to the map of processed nodes.
874 //Pointer to the map of predecessors arcs.
876 //Pointer to the map of distances.
878 //Pointer to the source node.
884 /// This constructor does not require parameters, therefore it initiates
885 /// all of the attributes to default values (0, INVALID).
886 DfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0),
887 _dist(0), _source(INVALID) {}
891 /// This constructor requires some parameters,
892 /// listed in the parameters list.
893 /// Others are initiated to 0.
894 /// \param g The digraph the algorithm runs on.
895 /// \param s The source node.
896 DfsWizardBase(const GR &g, Node s=INVALID) :
897 _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
898 _reached(0), _processed(0), _pred(0), _dist(0), _source(s) {}
902 /// Auxiliary class for the function type interface of DFS algorithm.
904 /// This auxiliary class is created to implement the function type
905 /// interface of \ref Dfs algorithm. It uses the functions and features
906 /// of the plain \ref Dfs, but it is much simpler to use it.
907 /// It should only be used through the \ref dfs() function, which makes
908 /// it easier to use the algorithm.
910 /// Simplicity means that the way to change the types defined
911 /// in the traits class is based on functions that returns the new class
912 /// and not on templatable built-in classes.
913 /// When using the plain \ref Dfs
914 /// the new class with the modified type comes from
915 /// the original class by using the ::
916 /// operator. In the case of \ref DfsWizard only
917 /// a function have to be called, and it will
918 /// return the needed class.
920 /// It does not have own \ref run() method. When its \ref run() method
921 /// is called, it initiates a plain \ref Dfs object, and calls the
922 /// \ref Dfs::run() method of it.
924 class DfsWizard : public TR
928 ///The type of the digraph the algorithm runs on.
929 typedef typename TR::Digraph Digraph;
931 typedef typename Digraph::Node Node;
932 typedef typename Digraph::NodeIt NodeIt;
933 typedef typename Digraph::Arc Arc;
934 typedef typename Digraph::OutArcIt OutArcIt;
936 ///\brief The type of the map that stores the predecessor
937 ///arcs of the shortest paths.
938 typedef typename TR::PredMap PredMap;
939 ///\brief The type of the map that stores the distances of the nodes.
940 typedef typename TR::DistMap DistMap;
941 ///\brief The type of the map that indicates which nodes are reached.
942 typedef typename TR::ReachedMap ReachedMap;
943 ///\brief The type of the map that indicates which nodes are processed.
944 typedef typename TR::ProcessedMap ProcessedMap;
949 DfsWizard() : TR() {}
951 /// Constructor that requires parameters.
953 /// Constructor that requires parameters.
954 /// These parameters will be the default values for the traits class.
955 DfsWizard(const Digraph &g, Node s=INVALID) :
959 DfsWizard(const TR &b) : TR(b) {}
963 ///Runs DFS algorithm from a source node.
965 ///Runs DFS algorithm from a source node.
966 ///The node can be given with the \ref source() function.
969 if(Base::_source==INVALID) throw UninitializedParameter();
970 Dfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
972 alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
974 alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
976 alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
978 alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
979 alg.run(Base::_source);
982 ///Runs DFS algorithm from the given node.
984 ///Runs DFS algorithm from the given node.
985 ///\param s is the given source.
992 /// Sets the source node, from which the Dfs algorithm runs.
994 /// Sets the source node, from which the Dfs algorithm runs.
995 /// \param s is the source node.
996 DfsWizard<TR> &source(Node s)
1003 struct DefPredMapBase : public Base {
1005 static PredMap *createPredMap(const Digraph &) { return 0; };
1006 DefPredMapBase(const TR &b) : TR(b) {}
1008 ///\brief \ref named-templ-param "Named parameter"
1009 ///for setting \ref PredMap object.
1011 ///\ref named-templ-param "Named parameter"
1012 ///for setting \ref PredMap object.
1014 DfsWizard<DefPredMapBase<T> > predMap(const T &t)
1016 Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1017 return DfsWizard<DefPredMapBase<T> >(*this);
1021 struct DefReachedMapBase : public Base {
1022 typedef T ReachedMap;
1023 static ReachedMap *createReachedMap(const Digraph &) { return 0; };
1024 DefReachedMapBase(const TR &b) : TR(b) {}
1026 ///\brief \ref named-templ-param "Named parameter"
1027 ///for setting \ref ReachedMap object.
1029 /// \ref named-templ-param "Named parameter"
1030 ///for setting \ref ReachedMap object.
1032 DfsWizard<DefReachedMapBase<T> > reachedMap(const T &t)
1034 Base::_reached=reinterpret_cast<void*>(const_cast<T*>(&t));
1035 return DfsWizard<DefReachedMapBase<T> >(*this);
1039 struct DefProcessedMapBase : public Base {
1040 typedef T ProcessedMap;
1041 static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
1042 DefProcessedMapBase(const TR &b) : TR(b) {}
1044 ///\brief \ref named-templ-param "Named parameter"
1045 ///for setting \ref ProcessedMap object.
1047 /// \ref named-templ-param "Named parameter"
1048 ///for setting \ref ProcessedMap object.
1050 DfsWizard<DefProcessedMapBase<T> > processedMap(const T &t)
1052 Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1053 return DfsWizard<DefProcessedMapBase<T> >(*this);
1057 struct DefDistMapBase : public Base {
1059 static DistMap *createDistMap(const Digraph &) { return 0; };
1060 DefDistMapBase(const TR &b) : TR(b) {}
1062 ///\brief \ref named-templ-param "Named parameter"
1063 ///for setting \ref DistMap object.
1065 ///\ref named-templ-param "Named parameter"
1066 ///for setting \ref DistMap object.
1068 DfsWizard<DefDistMapBase<T> > distMap(const T &t)
1070 Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1071 return DfsWizard<DefDistMapBase<T> >(*this);
1076 ///Function type interface for Dfs algorithm.
1079 ///Function type interface for Dfs algorithm.
1081 ///This function also has several
1082 ///\ref named-templ-func-param "named parameters",
1083 ///they are declared as the members of class \ref DfsWizard.
1085 ///example shows how to use these parameters.
1087 /// dfs(g,source).predMap(preds).run();
1089 ///\warning Don't forget to put the \ref DfsWizard::run() "run()"
1090 ///to the end of the parameter list.
1094 DfsWizard<DfsWizardBase<GR> >
1095 dfs(const GR &g,typename GR::Node s=INVALID)
1097 return DfsWizard<DfsWizardBase<GR> >(g,s);
1101 /// \brief Visitor class for DFS.
1103 /// This class defines the interface of the DfsVisit events, and
1104 /// it could be the base of a real visitor class.
1105 template <typename _Digraph>
1107 typedef _Digraph Digraph;
1108 typedef typename Digraph::Arc Arc;
1109 typedef typename Digraph::Node Node;
1110 /// \brief Called for the source node of the DFS.
1112 /// This function is called for the source node of the DFS.
1113 void start(const Node& node) {}
1114 /// \brief Called when the source node is leaved.
1116 /// This function is called when the source node is leaved.
1117 void stop(const Node& node) {}
1118 /// \brief Called when a node is reached first time.
1120 /// This function is called when a node is reached first time.
1121 void reach(const Node& node) {}
1122 /// \brief Called when an arc reaches a new node.
1124 /// This function is called when the DFS finds an arc whose target node
1125 /// is not reached yet.
1126 void discover(const Arc& arc) {}
1127 /// \brief Called when an arc is examined but its target node is
1128 /// already discovered.
1130 /// This function is called when an arc is examined but its target node is
1131 /// already discovered.
1132 void examine(const Arc& arc) {}
1133 /// \brief Called when the DFS steps back from a node.
1135 /// This function is called when the DFS steps back from a node.
1136 void leave(const Node& node) {}
1137 /// \brief Called when the DFS steps back on an arc.
1139 /// This function is called when the DFS steps back on an arc.
1140 void backtrack(const Arc& arc) {}
1143 template <typename _Digraph>
1145 typedef _Digraph Digraph;
1146 typedef typename Digraph::Arc Arc;
1147 typedef typename Digraph::Node Node;
1148 void start(const Node&) {}
1149 void stop(const Node&) {}
1150 void reach(const Node&) {}
1151 void discover(const Arc&) {}
1152 void examine(const Arc&) {}
1153 void leave(const Node&) {}
1154 void backtrack(const Arc&) {}
1156 template <typename _Visitor>
1157 struct Constraints {
1158 void constraints() {
1161 visitor.start(node);
1163 visitor.reach(node);
1164 visitor.discover(arc);
1165 visitor.examine(arc);
1166 visitor.leave(node);
1167 visitor.backtrack(arc);
1174 /// \brief Default traits class of DfsVisit class.
1176 /// Default traits class of DfsVisit class.
1177 /// \tparam _Digraph The type of the digraph the algorithm runs on.
1178 template<class _Digraph>
1179 struct DfsVisitDefaultTraits {
1181 /// \brief The type of the digraph the algorithm runs on.
1182 typedef _Digraph Digraph;
1184 /// \brief The type of the map that indicates which nodes are reached.
1186 /// The type of the map that indicates which nodes are reached.
1187 /// It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
1188 typedef typename Digraph::template NodeMap<bool> ReachedMap;
1190 /// \brief Instantiates a \ref ReachedMap.
1192 /// This function instantiates a \ref ReachedMap.
1193 /// \param digraph is the digraph, to which
1194 /// we would like to define the \ref ReachedMap.
1195 static ReachedMap *createReachedMap(const Digraph &digraph) {
1196 return new ReachedMap(digraph);
1203 /// \brief %DFS algorithm class with visitor interface.
1205 /// This class provides an efficient implementation of the %DFS algorithm
1206 /// with visitor interface.
1208 /// The %DfsVisit class provides an alternative interface to the Dfs
1209 /// class. It works with callback mechanism, the DfsVisit object calls
1210 /// the member functions of the \c Visitor class on every DFS event.
1212 /// \tparam _Digraph The type of the digraph the algorithm runs on.
1213 /// The default value is
1214 /// \ref ListDigraph. The value of _Digraph is not used directly by
1215 /// \ref DfsVisit, it is only passed to \ref DfsVisitDefaultTraits.
1216 /// \tparam _Visitor The Visitor type that is used by the algorithm.
1217 /// \ref DfsVisitor "DfsVisitor<_Digraph>" is an empty visitor, which
1218 /// does not observe the DFS events. If you want to observe the DFS
1219 /// events, you should implement your own visitor class.
1220 /// \tparam _Traits Traits class to set various data types used by the
1221 /// algorithm. The default traits class is
1222 /// \ref DfsVisitDefaultTraits "DfsVisitDefaultTraits<_Digraph>".
1223 /// See \ref DfsVisitDefaultTraits for the documentation of
1224 /// a DFS visit traits class.
1226 template <typename _Digraph, typename _Visitor, typename _Traits>
1228 template <typename _Digraph = ListDigraph,
1229 typename _Visitor = DfsVisitor<_Digraph>,
1230 typename _Traits = DfsDefaultTraits<_Digraph> >
1235 /// \brief \ref Exception for uninitialized parameters.
1237 /// This error represents problems in the initialization
1238 /// of the parameters of the algorithm.
1239 class UninitializedParameter : public lemon::UninitializedParameter {
1241 virtual const char* what() const throw()
1243 return "lemon::DfsVisit::UninitializedParameter";
1247 ///The traits class.
1248 typedef _Traits Traits;
1250 ///The type of the digraph the algorithm runs on.
1251 typedef typename Traits::Digraph Digraph;
1253 ///The visitor type used by the algorithm.
1254 typedef _Visitor Visitor;
1256 ///The type of the map that indicates which nodes are reached.
1257 typedef typename Traits::ReachedMap ReachedMap;
1261 typedef typename Digraph::Node Node;
1262 typedef typename Digraph::NodeIt NodeIt;
1263 typedef typename Digraph::Arc Arc;
1264 typedef typename Digraph::OutArcIt OutArcIt;
1266 //Pointer to the underlying digraph.
1267 const Digraph *_digraph;
1268 //Pointer to the visitor object.
1270 //Pointer to the map of reached status of the nodes.
1271 ReachedMap *_reached;
1272 //Indicates if _reached is locally allocated (true) or not.
1275 std::vector<typename Digraph::Arc> _stack;
1278 ///Creates the maps if necessary.
1279 ///\todo Better memory allocation (instead of new).
1280 void create_maps() {
1282 local_reached = true;
1283 _reached = Traits::createReachedMap(*_digraph);
1293 typedef DfsVisit Create;
1295 /// \name Named template parameters
1299 struct DefReachedMapTraits : public Traits {
1300 typedef T ReachedMap;
1301 static ReachedMap *createReachedMap(const Digraph &digraph) {
1302 throw UninitializedParameter();
1305 /// \brief \ref named-templ-param "Named parameter" for setting
1306 /// ReachedMap type.
1308 /// \ref named-templ-param "Named parameter" for setting ReachedMap type.
1310 struct DefReachedMap : public DfsVisit< Digraph, Visitor,
1311 DefReachedMapTraits<T> > {
1312 typedef DfsVisit< Digraph, Visitor, DefReachedMapTraits<T> > Create;
1318 /// \brief Constructor.
1322 /// \param digraph The digraph the algorithm runs on.
1323 /// \param visitor The visitor object of the algorithm.
1324 DfsVisit(const Digraph& digraph, Visitor& visitor)
1325 : _digraph(&digraph), _visitor(&visitor),
1326 _reached(0), local_reached(false) {}
1328 /// \brief Destructor.
1330 if(local_reached) delete _reached;
1333 /// \brief Sets the map that indicates which nodes are reached.
1335 /// Sets the map that indicates which nodes are reached.
1336 /// If you don't use this function before calling \ref run(),
1337 /// it will allocate one. The destructor deallocates this
1338 /// automatically allocated map, of course.
1339 /// \return <tt> (*this) </tt>
1340 DfsVisit &reachedMap(ReachedMap &m) {
1343 local_reached=false;
1351 /// \name Execution control
1352 /// The simplest way to execute the algorithm is to use
1353 /// one of the member functions called \ref lemon::DfsVisit::run()
1356 /// If you need more control on the execution, first you must call
1357 /// \ref lemon::DfsVisit::init() "init()", then you can add several
1358 /// source nodes with \ref lemon::DfsVisit::addSource() "addSource()".
1359 /// Finally \ref lemon::DfsVisit::start() "start()" will perform the
1360 /// actual path computation.
1364 /// \brief Initializes the internal data structures.
1366 /// Initializes the internal data structures.
1369 _stack.resize(countNodes(*_digraph));
1371 for (NodeIt u(*_digraph) ; u != INVALID ; ++u) {
1372 _reached->set(u, false);
1376 ///Adds a new source node.
1378 ///Adds a new source node to the set of nodes to be processed.
1380 ///\pre The stack must be empty. (Otherwise the algorithm gives
1383 ///\warning Distances will be wrong (or at least strange) in case of
1384 ///multiple sources.
1385 void addSource(Node s)
1387 LEMON_DEBUG(emptyQueue(), "The stack is not empty.");
1388 if(!(*_reached)[s]) {
1389 _reached->set(s,true);
1393 _digraph->firstOut(e, s);
1395 _stack[++_stack_head] = e;
1402 /// \brief Processes the next arc.
1404 /// Processes the next arc.
1406 /// \return The processed arc.
1408 /// \pre The stack must not be empty.
1409 Arc processNextArc() {
1410 Arc e = _stack[_stack_head];
1411 Node m = _digraph->target(e);
1412 if(!(*_reached)[m]) {
1413 _visitor->discover(e);
1415 _reached->set(m, true);
1416 _digraph->firstOut(_stack[++_stack_head], m);
1418 _visitor->examine(e);
1419 m = _digraph->source(e);
1420 _digraph->nextOut(_stack[_stack_head]);
1422 while (_stack_head>=0 && _stack[_stack_head] == INVALID) {
1425 if (_stack_head >= 0) {
1426 _visitor->backtrack(_stack[_stack_head]);
1427 m = _digraph->source(_stack[_stack_head]);
1428 _digraph->nextOut(_stack[_stack_head]);
1436 /// \brief Next arc to be processed.
1438 /// Next arc to be processed.
1440 /// \return The next arc to be processed or INVALID if the stack is
1442 Arc nextArc() const {
1443 return _stack_head >= 0 ? _stack[_stack_head] : INVALID;
1446 /// \brief Returns \c false if there are nodes
1447 /// to be processed.
1449 /// Returns \c false if there are nodes
1450 /// to be processed in the queue (stack).
1451 bool emptyQueue() const { return _stack_head < 0; }
1453 /// \brief Returns the number of the nodes to be processed.
1455 /// Returns the number of the nodes to be processed in the queue (stack).
1456 int queueSize() const { return _stack_head + 1; }
1458 /// \brief Executes the algorithm.
1460 /// Executes the algorithm.
1462 /// This method runs the %DFS algorithm from the root node
1463 /// in order to compute the %DFS path to each node.
1465 /// The algorithm computes
1466 /// - the %DFS tree,
1467 /// - the distance of each node from the root in the %DFS tree.
1469 /// \pre init() must be called and a root node should be
1470 /// added with addSource() before using this function.
1472 /// \note <tt>d.start()</tt> is just a shortcut of the following code.
1474 /// while ( !d.emptyQueue() ) {
1475 /// d.processNextArc();
1479 while ( !emptyQueue() ) processNextArc();
1482 /// \brief Executes the algorithm until the given target node is reached.
1484 /// Executes the algorithm until the given target node is reached.
1486 /// This method runs the %DFS algorithm from the root node
1487 /// in order to compute the DFS path to \c dest.
1489 /// The algorithm computes
1490 /// - the %DFS path to \c dest,
1491 /// - the distance of \c dest from the root in the %DFS tree.
1493 /// \pre init() must be called and a root node should be added
1494 /// with addSource() before using this function.
1495 void start(Node dest) {
1496 while ( !emptyQueue() && _digraph->target(_stack[_stack_head]) != dest )
1500 /// \brief Executes the algorithm until a condition is met.
1502 /// Executes the algorithm until a condition is met.
1504 /// This method runs the %DFS algorithm from the root node
1505 /// until an arc \c a with <tt>am[a]</tt> true is found.
1507 /// \param am A \c bool (or convertible) arc map. The algorithm
1508 /// will stop when it reaches an arc \c a with <tt>am[a]</tt> true.
1510 /// \return The reached arc \c a with <tt>am[a]</tt> true or
1511 /// \c INVALID if no such arc was found.
1513 /// \pre init() must be called and a root node should be added
1514 /// with addSource() before using this function.
1516 /// \warning Contrary to \ref Bfs and \ref Dijkstra, \c am is an arc map,
1518 template <typename AM>
1519 Arc start(const AM &am) {
1520 while ( !emptyQueue() && !am[_stack[_stack_head]] )
1522 return emptyQueue() ? INVALID : _stack[_stack_head];
1525 /// \brief Runs the algorithm from the given node.
1527 /// This method runs the %DFS algorithm from node \c s.
1528 /// in order to compute the DFS path to each node.
1530 /// The algorithm computes
1531 /// - the %DFS tree,
1532 /// - the distance of each node from the root in the %DFS tree.
1534 /// \note <tt>d.run(s)</tt> is just a shortcut of the following code.
1546 /// \brief Finds the %DFS path between \c s and \c t.
1548 /// This method runs the %DFS algorithm from node \c s
1549 /// in order to compute the DFS path to \c t.
1551 /// \return The length of the <tt>s</tt>--<tt>t</tt> DFS path,
1552 /// if \c t is reachable form \c s, \c 0 otherwise.
1554 /// \note Apart from the return value, <tt>d.run(s,t)</tt> is
1555 /// just a shortcut of the following code.
1561 int run(Node s,Node t) {
1565 return reached(t)?_stack_head+1:0;
1568 /// \brief Runs the algorithm to visit all nodes in the digraph.
1570 /// This method runs the %DFS algorithm in order to
1571 /// compute the %DFS path to each node.
1573 /// The algorithm computes
1574 /// - the %DFS tree,
1575 /// - the distance of each node from the root in the %DFS tree.
1577 /// \note <tt>d.run()</tt> is just a shortcut of the following code.
1580 /// for (NodeIt n(digraph); n != INVALID; ++n) {
1581 /// if (!d.reached(n)) {
1589 for (NodeIt it(*_digraph); it != INVALID; ++it) {
1599 /// \name Query Functions
1600 /// The result of the %DFS algorithm can be obtained using these
1602 /// Either \ref lemon::DfsVisit::run() "run()" or
1603 /// \ref lemon::DfsVisit::start() "start()" must be called before
1607 /// \brief Checks if a node is reachable from the root(s).
1609 /// Returns \c true if \c v is reachable from the root(s).
1610 /// \pre Either \ref run() or \ref start()
1611 /// must be called before using this function.
1612 bool reached(Node v) { return (*_reached)[v]; }
1618 } //END OF NAMESPACE LEMON