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 /// This interface of the DFS algorithm should be used in special cases
1213 /// when extra actions have to be performed in connection with certain
1214 /// events of the DFS algorithm. Otherwise consider to use Dfs or dfs()
1217 /// \tparam _Digraph The type of the digraph the algorithm runs on.
1218 /// The default value is
1219 /// \ref ListDigraph. The value of _Digraph is not used directly by
1220 /// \ref DfsVisit, it is only passed to \ref DfsVisitDefaultTraits.
1221 /// \tparam _Visitor The Visitor type that is used by the algorithm.
1222 /// \ref DfsVisitor "DfsVisitor<_Digraph>" is an empty visitor, which
1223 /// does not observe the DFS events. If you want to observe the DFS
1224 /// events, you should implement your own visitor class.
1225 /// \tparam _Traits Traits class to set various data types used by the
1226 /// algorithm. The default traits class is
1227 /// \ref DfsVisitDefaultTraits "DfsVisitDefaultTraits<_Digraph>".
1228 /// See \ref DfsVisitDefaultTraits for the documentation of
1229 /// a DFS visit traits class.
1231 template <typename _Digraph, typename _Visitor, typename _Traits>
1233 template <typename _Digraph = ListDigraph,
1234 typename _Visitor = DfsVisitor<_Digraph>,
1235 typename _Traits = DfsDefaultTraits<_Digraph> >
1240 /// \brief \ref Exception for uninitialized parameters.
1242 /// This error represents problems in the initialization
1243 /// of the parameters of the algorithm.
1244 class UninitializedParameter : public lemon::UninitializedParameter {
1246 virtual const char* what() const throw()
1248 return "lemon::DfsVisit::UninitializedParameter";
1252 ///The traits class.
1253 typedef _Traits Traits;
1255 ///The type of the digraph the algorithm runs on.
1256 typedef typename Traits::Digraph Digraph;
1258 ///The visitor type used by the algorithm.
1259 typedef _Visitor Visitor;
1261 ///The type of the map that indicates which nodes are reached.
1262 typedef typename Traits::ReachedMap ReachedMap;
1266 typedef typename Digraph::Node Node;
1267 typedef typename Digraph::NodeIt NodeIt;
1268 typedef typename Digraph::Arc Arc;
1269 typedef typename Digraph::OutArcIt OutArcIt;
1271 //Pointer to the underlying digraph.
1272 const Digraph *_digraph;
1273 //Pointer to the visitor object.
1275 //Pointer to the map of reached status of the nodes.
1276 ReachedMap *_reached;
1277 //Indicates if _reached is locally allocated (true) or not.
1280 std::vector<typename Digraph::Arc> _stack;
1283 ///Creates the maps if necessary.
1284 ///\todo Better memory allocation (instead of new).
1285 void create_maps() {
1287 local_reached = true;
1288 _reached = Traits::createReachedMap(*_digraph);
1298 typedef DfsVisit Create;
1300 /// \name Named template parameters
1304 struct DefReachedMapTraits : public Traits {
1305 typedef T ReachedMap;
1306 static ReachedMap *createReachedMap(const Digraph &digraph) {
1307 throw UninitializedParameter();
1310 /// \brief \ref named-templ-param "Named parameter" for setting
1311 /// ReachedMap type.
1313 /// \ref named-templ-param "Named parameter" for setting ReachedMap type.
1315 struct DefReachedMap : public DfsVisit< Digraph, Visitor,
1316 DefReachedMapTraits<T> > {
1317 typedef DfsVisit< Digraph, Visitor, DefReachedMapTraits<T> > Create;
1323 /// \brief Constructor.
1327 /// \param digraph The digraph the algorithm runs on.
1328 /// \param visitor The visitor object of the algorithm.
1329 DfsVisit(const Digraph& digraph, Visitor& visitor)
1330 : _digraph(&digraph), _visitor(&visitor),
1331 _reached(0), local_reached(false) {}
1333 /// \brief Destructor.
1335 if(local_reached) delete _reached;
1338 /// \brief Sets the map that indicates which nodes are reached.
1340 /// Sets the map that indicates which nodes are reached.
1341 /// If you don't use this function before calling \ref run(),
1342 /// it will allocate one. The destructor deallocates this
1343 /// automatically allocated map, of course.
1344 /// \return <tt> (*this) </tt>
1345 DfsVisit &reachedMap(ReachedMap &m) {
1348 local_reached=false;
1356 /// \name Execution control
1357 /// The simplest way to execute the algorithm is to use
1358 /// one of the member functions called \ref lemon::DfsVisit::run()
1361 /// If you need more control on the execution, first you must call
1362 /// \ref lemon::DfsVisit::init() "init()", then you can add several
1363 /// source nodes with \ref lemon::DfsVisit::addSource() "addSource()".
1364 /// Finally \ref lemon::DfsVisit::start() "start()" will perform the
1365 /// actual path computation.
1369 /// \brief Initializes the internal data structures.
1371 /// Initializes the internal data structures.
1374 _stack.resize(countNodes(*_digraph));
1376 for (NodeIt u(*_digraph) ; u != INVALID ; ++u) {
1377 _reached->set(u, false);
1381 ///Adds a new source node.
1383 ///Adds a new source node to the set of nodes to be processed.
1385 ///\pre The stack must be empty. (Otherwise the algorithm gives
1388 ///\warning Distances will be wrong (or at least strange) in case of
1389 ///multiple sources.
1390 void addSource(Node s)
1392 LEMON_DEBUG(emptyQueue(), "The stack is not empty.");
1393 if(!(*_reached)[s]) {
1394 _reached->set(s,true);
1398 _digraph->firstOut(e, s);
1400 _stack[++_stack_head] = e;
1407 /// \brief Processes the next arc.
1409 /// Processes the next arc.
1411 /// \return The processed arc.
1413 /// \pre The stack must not be empty.
1414 Arc processNextArc() {
1415 Arc e = _stack[_stack_head];
1416 Node m = _digraph->target(e);
1417 if(!(*_reached)[m]) {
1418 _visitor->discover(e);
1420 _reached->set(m, true);
1421 _digraph->firstOut(_stack[++_stack_head], m);
1423 _visitor->examine(e);
1424 m = _digraph->source(e);
1425 _digraph->nextOut(_stack[_stack_head]);
1427 while (_stack_head>=0 && _stack[_stack_head] == INVALID) {
1430 if (_stack_head >= 0) {
1431 _visitor->backtrack(_stack[_stack_head]);
1432 m = _digraph->source(_stack[_stack_head]);
1433 _digraph->nextOut(_stack[_stack_head]);
1441 /// \brief Next arc to be processed.
1443 /// Next arc to be processed.
1445 /// \return The next arc to be processed or INVALID if the stack is
1447 Arc nextArc() const {
1448 return _stack_head >= 0 ? _stack[_stack_head] : INVALID;
1451 /// \brief Returns \c false if there are nodes
1452 /// to be processed.
1454 /// Returns \c false if there are nodes
1455 /// to be processed in the queue (stack).
1456 bool emptyQueue() const { return _stack_head < 0; }
1458 /// \brief Returns the number of the nodes to be processed.
1460 /// Returns the number of the nodes to be processed in the queue (stack).
1461 int queueSize() const { return _stack_head + 1; }
1463 /// \brief Executes the algorithm.
1465 /// Executes the algorithm.
1467 /// This method runs the %DFS algorithm from the root node
1468 /// in order to compute the %DFS path to each node.
1470 /// The algorithm computes
1471 /// - the %DFS tree,
1472 /// - the distance of each node from the root in the %DFS tree.
1474 /// \pre init() must be called and a root node should be
1475 /// added with addSource() before using this function.
1477 /// \note <tt>d.start()</tt> is just a shortcut of the following code.
1479 /// while ( !d.emptyQueue() ) {
1480 /// d.processNextArc();
1484 while ( !emptyQueue() ) processNextArc();
1487 /// \brief Executes the algorithm until the given target node is reached.
1489 /// Executes the algorithm until the given target node is reached.
1491 /// This method runs the %DFS algorithm from the root node
1492 /// in order to compute the DFS path to \c dest.
1494 /// The algorithm computes
1495 /// - the %DFS path to \c dest,
1496 /// - the distance of \c dest from the root in the %DFS tree.
1498 /// \pre init() must be called and a root node should be added
1499 /// with addSource() before using this function.
1500 void start(Node dest) {
1501 while ( !emptyQueue() && _digraph->target(_stack[_stack_head]) != dest )
1505 /// \brief Executes the algorithm until a condition is met.
1507 /// Executes the algorithm until a condition is met.
1509 /// This method runs the %DFS algorithm from the root node
1510 /// until an arc \c a with <tt>am[a]</tt> true is found.
1512 /// \param am A \c bool (or convertible) arc map. The algorithm
1513 /// will stop when it reaches an arc \c a with <tt>am[a]</tt> true.
1515 /// \return The reached arc \c a with <tt>am[a]</tt> true or
1516 /// \c INVALID if no such arc was found.
1518 /// \pre init() must be called and a root node should be added
1519 /// with addSource() before using this function.
1521 /// \warning Contrary to \ref Bfs and \ref Dijkstra, \c am is an arc map,
1523 template <typename AM>
1524 Arc start(const AM &am) {
1525 while ( !emptyQueue() && !am[_stack[_stack_head]] )
1527 return emptyQueue() ? INVALID : _stack[_stack_head];
1530 /// \brief Runs the algorithm from the given node.
1532 /// This method runs the %DFS algorithm from node \c s.
1533 /// in order to compute the DFS path to each node.
1535 /// The algorithm computes
1536 /// - the %DFS tree,
1537 /// - the distance of each node from the root in the %DFS tree.
1539 /// \note <tt>d.run(s)</tt> is just a shortcut of the following code.
1551 /// \brief Finds the %DFS path between \c s and \c t.
1553 /// This method runs the %DFS algorithm from node \c s
1554 /// in order to compute the DFS path to \c t.
1556 /// \return The length of the <tt>s</tt>--<tt>t</tt> DFS path,
1557 /// if \c t is reachable form \c s, \c 0 otherwise.
1559 /// \note Apart from the return value, <tt>d.run(s,t)</tt> is
1560 /// just a shortcut of the following code.
1566 int run(Node s,Node t) {
1570 return reached(t)?_stack_head+1:0;
1573 /// \brief Runs the algorithm to visit all nodes in the digraph.
1575 /// This method runs the %DFS algorithm in order to
1576 /// compute the %DFS path to each node.
1578 /// The algorithm computes
1579 /// - the %DFS tree,
1580 /// - the distance of each node from the root in the %DFS tree.
1582 /// \note <tt>d.run()</tt> is just a shortcut of the following code.
1585 /// for (NodeIt n(digraph); n != INVALID; ++n) {
1586 /// if (!d.reached(n)) {
1594 for (NodeIt it(*_digraph); it != INVALID; ++it) {
1604 /// \name Query Functions
1605 /// The result of the %DFS algorithm can be obtained using these
1607 /// Either \ref lemon::DfsVisit::run() "run()" or
1608 /// \ref lemon::DfsVisit::start() "start()" must be called before
1612 /// \brief Checks if a node is reachable from the root(s).
1614 /// Returns \c true if \c v is reachable from the root(s).
1615 /// \pre Either \ref run() or \ref start()
1616 /// must be called before using this function.
1617 bool reached(Node v) { return (*_reached)[v]; }
1623 } //END OF NAMESPACE LEMON