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/maps.h>
31 #include <lemon/path.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 PredMap.
54 ///This function instantiates a PredMap.
55 ///\param g is the digraph, to which we would like to define the
57 static PredMap *createPredMap(const Digraph &g)
59 return new PredMap(g);
62 ///The type of the map that indicates which nodes are processed.
64 ///The type of the map that indicates which nodes are processed.
65 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
66 typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
67 ///Instantiates a ProcessedMap.
69 ///This function instantiates a ProcessedMap.
70 ///\param g is the digraph, to which
71 ///we would like to define the ProcessedMap
73 static ProcessedMap *createProcessedMap(const Digraph &g)
75 static ProcessedMap *createProcessedMap(const Digraph &)
78 return new ProcessedMap();
81 ///The type of the map that indicates which nodes are reached.
83 ///The type of the map that indicates which nodes are reached.
84 ///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
85 typedef typename Digraph::template NodeMap<bool> ReachedMap;
86 ///Instantiates a ReachedMap.
88 ///This function instantiates a ReachedMap.
89 ///\param g is the digraph, to which
90 ///we would like to define the ReachedMap.
91 static ReachedMap *createReachedMap(const Digraph &g)
93 return new ReachedMap(g);
96 ///The type of the map that stores the distances of the nodes.
98 ///The type of the map that stores the distances of the nodes.
99 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
100 typedef typename Digraph::template NodeMap<int> DistMap;
101 ///Instantiates a DistMap.
103 ///This function instantiates a DistMap.
104 ///\param g is the digraph, to which we would like to define the
106 static DistMap *createDistMap(const Digraph &g)
108 return new DistMap(g);
112 ///%DFS algorithm class.
115 ///This class provides an efficient implementation of the %DFS algorithm.
117 ///There is also a \ref dfs() "function-type interface" for the DFS
118 ///algorithm, which is convenient in the simplier cases and it can be
121 ///\tparam GR The type of the digraph the algorithm runs on.
122 ///The default type is \ref ListDigraph.
124 template <typename GR,
127 template <typename GR=ListDigraph,
128 typename TR=DfsDefaultTraits<GR> >
133 ///The type of the digraph the algorithm runs on.
134 typedef typename TR::Digraph Digraph;
136 ///\brief The type of the map that stores the predecessor arcs of the
138 typedef typename TR::PredMap PredMap;
139 ///The type of the map that stores the distances of the nodes.
140 typedef typename TR::DistMap DistMap;
141 ///The type of the map that indicates which nodes are reached.
142 typedef typename TR::ReachedMap ReachedMap;
143 ///The type of the map that indicates which nodes are processed.
144 typedef typename TR::ProcessedMap ProcessedMap;
145 ///The type of the paths.
146 typedef PredMapPath<Digraph, PredMap> Path;
148 ///The \ref DfsDefaultTraits "traits class" of the algorithm.
153 typedef typename Digraph::Node Node;
154 typedef typename Digraph::NodeIt NodeIt;
155 typedef typename Digraph::Arc Arc;
156 typedef typename Digraph::OutArcIt OutArcIt;
158 //Pointer to the underlying digraph.
160 //Pointer to the map of predecessor arcs.
162 //Indicates if _pred is locally allocated (true) or not.
164 //Pointer to the map of distances.
166 //Indicates if _dist is locally allocated (true) or not.
168 //Pointer to the map of reached status of the nodes.
169 ReachedMap *_reached;
170 //Indicates if _reached is locally allocated (true) or not.
172 //Pointer to the map of processed status of the nodes.
173 ProcessedMap *_processed;
174 //Indicates if _processed is locally allocated (true) or not.
175 bool local_processed;
177 std::vector<typename Digraph::OutArcIt> _stack;
180 //Creates the maps if necessary.
185 _pred = Traits::createPredMap(*G);
189 _dist = Traits::createDistMap(*G);
192 local_reached = true;
193 _reached = Traits::createReachedMap(*G);
196 local_processed = true;
197 _processed = Traits::createProcessedMap(*G);
209 ///\name Named template parameters
214 struct SetPredMapTraits : public Traits {
216 static PredMap *createPredMap(const Digraph &)
218 LEMON_ASSERT(false, "PredMap is not initialized");
219 return 0; // ignore warnings
222 ///\brief \ref named-templ-param "Named parameter" for setting
225 ///\ref named-templ-param "Named parameter" for setting
227 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
229 struct SetPredMap : public Dfs<Digraph, SetPredMapTraits<T> > {
230 typedef Dfs<Digraph, SetPredMapTraits<T> > Create;
234 struct SetDistMapTraits : public Traits {
236 static DistMap *createDistMap(const Digraph &)
238 LEMON_ASSERT(false, "DistMap is not initialized");
239 return 0; // ignore warnings
242 ///\brief \ref named-templ-param "Named parameter" for setting
245 ///\ref named-templ-param "Named parameter" for setting
247 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
249 struct SetDistMap : public Dfs< Digraph, SetDistMapTraits<T> > {
250 typedef Dfs<Digraph, SetDistMapTraits<T> > Create;
254 struct SetReachedMapTraits : public Traits {
255 typedef T ReachedMap;
256 static ReachedMap *createReachedMap(const Digraph &)
258 LEMON_ASSERT(false, "ReachedMap is not initialized");
259 return 0; // ignore warnings
262 ///\brief \ref named-templ-param "Named parameter" for setting
265 ///\ref named-templ-param "Named parameter" for setting
267 ///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
269 struct SetReachedMap : public Dfs< Digraph, SetReachedMapTraits<T> > {
270 typedef Dfs< Digraph, SetReachedMapTraits<T> > Create;
274 struct SetProcessedMapTraits : public Traits {
275 typedef T ProcessedMap;
276 static ProcessedMap *createProcessedMap(const Digraph &)
278 LEMON_ASSERT(false, "ProcessedMap is not initialized");
279 return 0; // ignore warnings
282 ///\brief \ref named-templ-param "Named parameter" for setting
283 ///ProcessedMap type.
285 ///\ref named-templ-param "Named parameter" for setting
286 ///ProcessedMap type.
287 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
289 struct SetProcessedMap : public Dfs< Digraph, SetProcessedMapTraits<T> > {
290 typedef Dfs< Digraph, SetProcessedMapTraits<T> > Create;
293 struct SetStandardProcessedMapTraits : public Traits {
294 typedef typename Digraph::template NodeMap<bool> ProcessedMap;
295 static ProcessedMap *createProcessedMap(const Digraph &g)
297 return new ProcessedMap(g);
300 ///\brief \ref named-templ-param "Named parameter" for setting
301 ///ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
303 ///\ref named-templ-param "Named parameter" for setting
304 ///ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
305 ///If you don't set it explicitly, it will be automatically allocated.
306 struct SetStandardProcessedMap :
307 public Dfs< Digraph, SetStandardProcessedMapTraits > {
308 typedef Dfs< Digraph, SetStandardProcessedMapTraits > Create;
318 ///\param g The digraph the algorithm runs on.
319 Dfs(const Digraph &g) :
321 _pred(NULL), local_pred(false),
322 _dist(NULL), local_dist(false),
323 _reached(NULL), local_reached(false),
324 _processed(NULL), local_processed(false)
330 if(local_pred) delete _pred;
331 if(local_dist) delete _dist;
332 if(local_reached) delete _reached;
333 if(local_processed) delete _processed;
336 ///Sets the map that stores the predecessor arcs.
338 ///Sets the map that stores the predecessor arcs.
339 ///If you don't use this function before calling \ref run(Node) "run()"
340 ///or \ref init(), an instance will be allocated automatically.
341 ///The destructor deallocates this automatically allocated map,
343 ///\return <tt> (*this) </tt>
344 Dfs &predMap(PredMap &m)
354 ///Sets the map that indicates which nodes are reached.
356 ///Sets the map that indicates which nodes are reached.
357 ///If you don't use this function before calling \ref run(Node) "run()"
358 ///or \ref init(), an instance will be allocated automatically.
359 ///The destructor deallocates this automatically allocated map,
361 ///\return <tt> (*this) </tt>
362 Dfs &reachedMap(ReachedMap &m)
372 ///Sets the map that indicates which nodes are processed.
374 ///Sets the map that indicates which nodes are processed.
375 ///If you don't use this function before calling \ref run(Node) "run()"
376 ///or \ref init(), an instance will be allocated automatically.
377 ///The destructor deallocates this automatically allocated map,
379 ///\return <tt> (*this) </tt>
380 Dfs &processedMap(ProcessedMap &m)
382 if(local_processed) {
384 local_processed=false;
390 ///Sets the map that stores the distances of the nodes.
392 ///Sets the map that stores the distances of the nodes calculated by
394 ///If you don't use this function before calling \ref run(Node) "run()"
395 ///or \ref init(), an instance will be allocated automatically.
396 ///The destructor deallocates this automatically allocated map,
398 ///\return <tt> (*this) </tt>
399 Dfs &distMap(DistMap &m)
411 ///\name Execution Control
412 ///The simplest way to execute the DFS algorithm is to use one of the
413 ///member functions called \ref run(Node) "run()".\n
414 ///If you need more control on the execution, first you have to call
415 ///\ref init(), then you can add a source node with \ref addSource()
416 ///and perform the actual computation with \ref start().
417 ///This procedure can be repeated if there are nodes that have not
422 ///\brief Initializes the internal data structures.
424 ///Initializes the internal data structures.
428 _stack.resize(countNodes(*G));
430 for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
431 _pred->set(u,INVALID);
432 _reached->set(u,false);
433 _processed->set(u,false);
437 ///Adds a new source node.
439 ///Adds a new source node to the set of nodes to be processed.
441 ///\pre The stack must be empty. Otherwise the algorithm gives
442 ///wrong results. (One of the outgoing arcs of all the source nodes
443 ///except for the last one will not be visited and distances will
445 void addSource(Node s)
447 LEMON_DEBUG(emptyQueue(), "The stack is not empty.");
450 _reached->set(s,true);
451 _pred->set(s,INVALID);
454 _stack[++_stack_head]=e;
455 _dist->set(s,_stack_head);
458 _processed->set(s,true);
464 ///Processes the next arc.
466 ///Processes the next arc.
468 ///\return The processed arc.
470 ///\pre The stack must not be empty.
474 Arc e=_stack[_stack_head];
475 if(!(*_reached)[m=G->target(e)]) {
477 _reached->set(m,true);
479 _stack[_stack_head] = OutArcIt(*G, m);
480 _dist->set(m,_stack_head);
484 ++_stack[_stack_head];
486 while(_stack_head>=0 && _stack[_stack_head]==INVALID) {
487 _processed->set(m,true);
490 m=G->source(_stack[_stack_head]);
491 ++_stack[_stack_head];
497 ///Next arc to be processed.
499 ///Next arc to be processed.
501 ///\return The next arc to be processed or \c INVALID if the stack
503 OutArcIt nextArc() const
505 return _stack_head>=0?_stack[_stack_head]:INVALID;
508 ///Returns \c false if there are nodes to be processed.
510 ///Returns \c false if there are nodes to be processed
511 ///in the queue (stack).
512 bool emptyQueue() const { return _stack_head<0; }
514 ///Returns the number of the nodes to be processed.
516 ///Returns the number of the nodes to be processed
517 ///in the queue (stack).
518 int queueSize() const { return _stack_head+1; }
520 ///Executes the algorithm.
522 ///Executes the algorithm.
524 ///This method runs the %DFS algorithm from the root node
525 ///in order to compute the DFS path to each node.
527 /// The algorithm computes
529 ///- the distance of each node from the root in the %DFS tree.
531 ///\pre init() must be called and a root node should be
532 ///added with addSource() before using this function.
534 ///\note <tt>d.start()</tt> is just a shortcut of the following code.
536 /// while ( !d.emptyQueue() ) {
537 /// d.processNextArc();
542 while ( !emptyQueue() ) processNextArc();
545 ///Executes the algorithm until the given target node is reached.
547 ///Executes the algorithm until the given target node is reached.
549 ///This method runs the %DFS algorithm from the root node
550 ///in order to compute the DFS path to \c t.
552 ///The algorithm computes
553 ///- the %DFS path to \c t,
554 ///- the distance of \c t from the root in the %DFS tree.
556 ///\pre init() must be called and a root node should be
557 ///added with addSource() before using this function.
560 while ( !emptyQueue() && G->target(_stack[_stack_head])!=t )
564 ///Executes the algorithm until a condition is met.
566 ///Executes the algorithm until a condition is met.
568 ///This method runs the %DFS algorithm from the root node
569 ///until an arc \c a with <tt>am[a]</tt> true is found.
571 ///\param am A \c bool (or convertible) arc map. The algorithm
572 ///will stop when it reaches an arc \c a with <tt>am[a]</tt> true.
574 ///\return The reached arc \c a with <tt>am[a]</tt> true or
575 ///\c INVALID if no such arc was found.
577 ///\pre init() must be called and a root node should be
578 ///added with addSource() before using this function.
580 ///\warning Contrary to \ref Bfs and \ref Dijkstra, \c am is an arc map,
582 template<class ArcBoolMap>
583 Arc start(const ArcBoolMap &am)
585 while ( !emptyQueue() && !am[_stack[_stack_head]] )
587 return emptyQueue() ? INVALID : _stack[_stack_head];
590 ///Runs the algorithm from the given source node.
592 ///This method runs the %DFS algorithm from node \c s
593 ///in order to compute the DFS path to each node.
595 ///The algorithm computes
597 ///- the distance of each node from the root in the %DFS tree.
599 ///\note <tt>d.run(s)</tt> is just a shortcut of the following code.
611 ///Finds the %DFS path between \c s and \c t.
613 ///This method runs the %DFS algorithm from node \c s
614 ///in order to compute the DFS path to node \c t
615 ///(it stops searching when \c t is processed)
617 ///\return \c true if \c t is reachable form \c s.
619 ///\note Apart from the return value, <tt>d.run(s,t)</tt> is
620 ///just a shortcut of the following code.
626 bool run(Node s,Node t) {
633 ///Runs the algorithm to visit all nodes in the digraph.
635 ///This method runs the %DFS algorithm in order to compute the
636 ///%DFS path to each node.
638 ///The algorithm computes
639 ///- the %DFS tree (forest),
640 ///- the distance of each node from the root(s) in the %DFS tree.
642 ///\note <tt>d.run()</tt> is just a shortcut of the following code.
645 /// for (NodeIt n(digraph); n != INVALID; ++n) {
646 /// if (!d.reached(n)) {
654 for (NodeIt it(*G); it != INVALID; ++it) {
664 ///\name Query Functions
665 ///The results of the DFS algorithm can be obtained using these
667 ///Either \ref run(Node) "run()" or \ref start() should be called
668 ///before using them.
672 ///The DFS path to a node.
674 ///Returns the DFS path to a node.
676 ///\warning \c t should be reached from the root(s).
678 ///\pre Either \ref run(Node) "run()" or \ref init()
679 ///must be called before using this function.
680 Path path(Node t) const { return Path(*G, *_pred, t); }
682 ///The distance of a node from the root(s).
684 ///Returns the distance of a node from the root(s).
686 ///\warning If node \c v is not reached from the root(s), then
687 ///the return value of this function is undefined.
689 ///\pre Either \ref run(Node) "run()" or \ref init()
690 ///must be called before using this function.
691 int dist(Node v) const { return (*_dist)[v]; }
693 ///Returns the 'previous arc' of the %DFS tree for a node.
695 ///This function returns the 'previous arc' of the %DFS tree for the
696 ///node \c v, i.e. it returns the last arc of a %DFS path from a
697 ///root to \c v. It is \c INVALID if \c v is not reached from the
698 ///root(s) or if \c v is a root.
700 ///The %DFS tree used here is equal to the %DFS tree used in
703 ///\pre Either \ref run(Node) "run()" or \ref init()
704 ///must be called before using this function.
705 Arc predArc(Node v) const { return (*_pred)[v];}
707 ///Returns the 'previous node' of the %DFS tree.
709 ///This function returns the 'previous node' of the %DFS
710 ///tree for the node \c v, i.e. it returns the last but one node
711 ///from a %DFS path from a root to \c v. It is \c INVALID
712 ///if \c v is not reached from the root(s) or if \c v is a root.
714 ///The %DFS tree used here is equal to the %DFS tree used in
717 ///\pre Either \ref run(Node) "run()" or \ref init()
718 ///must be called before using this function.
719 Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
720 G->source((*_pred)[v]); }
722 ///\brief Returns a const reference to the node map that stores the
723 ///distances of the nodes.
725 ///Returns a const reference to the node map that stores the
726 ///distances of the nodes calculated by the algorithm.
728 ///\pre Either \ref run(Node) "run()" or \ref init()
729 ///must be called before using this function.
730 const DistMap &distMap() const { return *_dist;}
732 ///\brief Returns a const reference to the node map that stores the
735 ///Returns a const reference to the node map that stores the predecessor
736 ///arcs, which form the DFS tree.
738 ///\pre Either \ref run(Node) "run()" or \ref init()
739 ///must be called before using this function.
740 const PredMap &predMap() const { return *_pred;}
742 ///Checks if a node is reached from the root(s).
744 ///Returns \c true if \c v is reached from the root(s).
746 ///\pre Either \ref run(Node) "run()" or \ref init()
747 ///must be called before using this function.
748 bool reached(Node v) const { return (*_reached)[v]; }
753 ///Default traits class of dfs() function.
755 ///Default traits class of dfs() function.
756 ///\tparam GR Digraph type.
758 struct DfsWizardDefaultTraits
760 ///The type of the digraph the algorithm runs on.
763 ///\brief The type of the map that stores the predecessor
764 ///arcs of the %DFS paths.
766 ///The type of the map that stores the predecessor
767 ///arcs of the %DFS paths.
768 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
769 typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
770 ///Instantiates a PredMap.
772 ///This function instantiates a PredMap.
773 ///\param g is the digraph, to which we would like to define the
775 static PredMap *createPredMap(const Digraph &g)
777 return new PredMap(g);
780 ///The type of the map that indicates which nodes are processed.
782 ///The type of the map that indicates which nodes are processed.
783 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
784 ///By default it is a NullMap.
785 typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
786 ///Instantiates a ProcessedMap.
788 ///This function instantiates a ProcessedMap.
789 ///\param g is the digraph, to which
790 ///we would like to define the ProcessedMap.
792 static ProcessedMap *createProcessedMap(const Digraph &g)
794 static ProcessedMap *createProcessedMap(const Digraph &)
797 return new ProcessedMap();
800 ///The type of the map that indicates which nodes are reached.
802 ///The type of the map that indicates which nodes are reached.
803 ///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
804 typedef typename Digraph::template NodeMap<bool> ReachedMap;
805 ///Instantiates a ReachedMap.
807 ///This function instantiates a ReachedMap.
808 ///\param g is the digraph, to which
809 ///we would like to define the ReachedMap.
810 static ReachedMap *createReachedMap(const Digraph &g)
812 return new ReachedMap(g);
815 ///The type of the map that stores the distances of the nodes.
817 ///The type of the map that stores the distances of the nodes.
818 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
819 typedef typename Digraph::template NodeMap<int> DistMap;
820 ///Instantiates a DistMap.
822 ///This function instantiates a DistMap.
823 ///\param g is the digraph, to which we would like to define
825 static DistMap *createDistMap(const Digraph &g)
827 return new DistMap(g);
830 ///The type of the DFS paths.
832 ///The type of the DFS paths.
833 ///It must meet the \ref concepts::Path "Path" concept.
834 typedef lemon::Path<Digraph> Path;
837 /// Default traits class used by DfsWizard
839 /// To make it easier to use Dfs algorithm
840 /// we have created a wizard class.
841 /// This \ref DfsWizard class needs default traits,
842 /// as well as the \ref Dfs class.
843 /// The \ref DfsWizardBase is a class to be the default traits of the
844 /// \ref DfsWizard class.
846 class DfsWizardBase : public DfsWizardDefaultTraits<GR>
849 typedef DfsWizardDefaultTraits<GR> Base;
851 //The type of the nodes in the digraph.
852 typedef typename Base::Digraph::Node Node;
854 //Pointer to the digraph the algorithm runs on.
856 //Pointer to the map of reached nodes.
858 //Pointer to the map of processed nodes.
860 //Pointer to the map of predecessors arcs.
862 //Pointer to the map of distances.
864 //Pointer to the DFS path to the target node.
866 //Pointer to the distance of the target node.
872 /// This constructor does not require parameters, therefore it initiates
873 /// all of the attributes to \c 0.
874 DfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0),
875 _dist(0), _path(0), _di(0) {}
879 /// This constructor requires one parameter,
880 /// others are initiated to \c 0.
881 /// \param g The digraph the algorithm runs on.
882 DfsWizardBase(const GR &g) :
883 _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
884 _reached(0), _processed(0), _pred(0), _dist(0), _path(0), _di(0) {}
888 /// Auxiliary class for the function-type interface of DFS algorithm.
890 /// This auxiliary class is created to implement the
891 /// \ref dfs() "function-type interface" of \ref Dfs algorithm.
892 /// It does not have own \ref run(Node) "run()" method, it uses the
893 /// functions and features of the plain \ref Dfs.
895 /// This class should only be used through the \ref dfs() function,
896 /// which makes it easier to use the algorithm.
898 class DfsWizard : public TR
902 ///The type of the digraph the algorithm runs on.
903 typedef typename TR::Digraph Digraph;
905 typedef typename Digraph::Node Node;
906 typedef typename Digraph::NodeIt NodeIt;
907 typedef typename Digraph::Arc Arc;
908 typedef typename Digraph::OutArcIt OutArcIt;
910 ///\brief The type of the map that stores the predecessor
911 ///arcs of the DFS paths.
912 typedef typename TR::PredMap PredMap;
913 ///\brief The type of the map that stores the distances of the nodes.
914 typedef typename TR::DistMap DistMap;
915 ///\brief The type of the map that indicates which nodes are reached.
916 typedef typename TR::ReachedMap ReachedMap;
917 ///\brief The type of the map that indicates which nodes are processed.
918 typedef typename TR::ProcessedMap ProcessedMap;
919 ///The type of the DFS paths
920 typedef typename TR::Path Path;
925 DfsWizard() : TR() {}
927 /// Constructor that requires parameters.
929 /// Constructor that requires parameters.
930 /// These parameters will be the default values for the traits class.
931 /// \param g The digraph the algorithm runs on.
932 DfsWizard(const Digraph &g) :
936 DfsWizard(const TR &b) : TR(b) {}
940 ///Runs DFS algorithm from the given source node.
942 ///This method runs DFS algorithm from node \c s
943 ///in order to compute the DFS path to each node.
946 Dfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
948 alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
950 alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
952 alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
953 if (Base::_processed)
954 alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
961 ///Finds the DFS path between \c s and \c t.
963 ///This method runs DFS algorithm from node \c s
964 ///in order to compute the DFS path to node \c t
965 ///(it stops searching when \c t is processed).
967 ///\return \c true if \c t is reachable form \c s.
968 bool run(Node s, Node t)
970 Dfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
972 alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
974 alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
976 alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
977 if (Base::_processed)
978 alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
981 *reinterpret_cast<Path*>(Base::_path) = alg.path(t);
983 *Base::_di = alg.dist(t);
984 return alg.reached(t);
987 ///Runs DFS algorithm to visit all nodes in the digraph.
989 ///This method runs DFS algorithm in order to compute
990 ///the DFS path to each node.
997 struct SetPredMapBase : public Base {
999 static PredMap *createPredMap(const Digraph &) { return 0; };
1000 SetPredMapBase(const TR &b) : TR(b) {}
1002 ///\brief \ref named-func-param "Named parameter"
1003 ///for setting PredMap object.
1005 ///\ref named-func-param "Named parameter"
1006 ///for setting PredMap object.
1008 DfsWizard<SetPredMapBase<T> > predMap(const T &t)
1010 Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1011 return DfsWizard<SetPredMapBase<T> >(*this);
1015 struct SetReachedMapBase : public Base {
1016 typedef T ReachedMap;
1017 static ReachedMap *createReachedMap(const Digraph &) { return 0; };
1018 SetReachedMapBase(const TR &b) : TR(b) {}
1020 ///\brief \ref named-func-param "Named parameter"
1021 ///for setting ReachedMap object.
1023 /// \ref named-func-param "Named parameter"
1024 ///for setting ReachedMap object.
1026 DfsWizard<SetReachedMapBase<T> > reachedMap(const T &t)
1028 Base::_reached=reinterpret_cast<void*>(const_cast<T*>(&t));
1029 return DfsWizard<SetReachedMapBase<T> >(*this);
1033 struct SetDistMapBase : public Base {
1035 static DistMap *createDistMap(const Digraph &) { return 0; };
1036 SetDistMapBase(const TR &b) : TR(b) {}
1038 ///\brief \ref named-func-param "Named parameter"
1039 ///for setting DistMap object.
1041 /// \ref named-func-param "Named parameter"
1042 ///for setting DistMap object.
1044 DfsWizard<SetDistMapBase<T> > distMap(const T &t)
1046 Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1047 return DfsWizard<SetDistMapBase<T> >(*this);
1051 struct SetProcessedMapBase : public Base {
1052 typedef T ProcessedMap;
1053 static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
1054 SetProcessedMapBase(const TR &b) : TR(b) {}
1056 ///\brief \ref named-func-param "Named parameter"
1057 ///for setting ProcessedMap object.
1059 /// \ref named-func-param "Named parameter"
1060 ///for setting ProcessedMap object.
1062 DfsWizard<SetProcessedMapBase<T> > processedMap(const T &t)
1064 Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1065 return DfsWizard<SetProcessedMapBase<T> >(*this);
1069 struct SetPathBase : public Base {
1071 SetPathBase(const TR &b) : TR(b) {}
1073 ///\brief \ref named-func-param "Named parameter"
1074 ///for getting the DFS path to the target node.
1076 ///\ref named-func-param "Named parameter"
1077 ///for getting the DFS path to the target node.
1079 DfsWizard<SetPathBase<T> > path(const T &t)
1081 Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t));
1082 return DfsWizard<SetPathBase<T> >(*this);
1085 ///\brief \ref named-func-param "Named parameter"
1086 ///for getting the distance of the target node.
1088 ///\ref named-func-param "Named parameter"
1089 ///for getting the distance of the target node.
1090 DfsWizard dist(const int &d)
1092 Base::_di=const_cast<int*>(&d);
1098 ///Function-type interface for DFS algorithm.
1101 ///Function-type interface for DFS algorithm.
1103 ///This function also has several \ref named-func-param "named parameters",
1104 ///they are declared as the members of class \ref DfsWizard.
1105 ///The following examples show how to use these parameters.
1107 /// // Compute the DFS tree
1108 /// dfs(g).predMap(preds).distMap(dists).run(s);
1110 /// // Compute the DFS path from s to t
1111 /// bool reached = dfs(g).path(p).dist(d).run(s,t);
1113 ///\warning Don't forget to put the \ref DfsWizard::run(Node) "run()"
1114 ///to the end of the parameter list.
1118 DfsWizard<DfsWizardBase<GR> >
1119 dfs(const GR &digraph)
1121 return DfsWizard<DfsWizardBase<GR> >(digraph);
1125 /// \brief Visitor class for DFS.
1127 /// This class defines the interface of the DfsVisit events, and
1128 /// it could be the base of a real visitor class.
1129 template <typename _Digraph>
1131 typedef _Digraph Digraph;
1132 typedef typename Digraph::Arc Arc;
1133 typedef typename Digraph::Node Node;
1134 /// \brief Called for the source node of the DFS.
1136 /// This function is called for the source node of the DFS.
1137 void start(const Node& node) {}
1138 /// \brief Called when the source node is leaved.
1140 /// This function is called when the source node is leaved.
1141 void stop(const Node& node) {}
1142 /// \brief Called when a node is reached first time.
1144 /// This function is called when a node is reached first time.
1145 void reach(const Node& node) {}
1146 /// \brief Called when an arc reaches a new node.
1148 /// This function is called when the DFS finds an arc whose target node
1149 /// is not reached yet.
1150 void discover(const Arc& arc) {}
1151 /// \brief Called when an arc is examined but its target node is
1152 /// already discovered.
1154 /// This function is called when an arc is examined but its target node is
1155 /// already discovered.
1156 void examine(const Arc& arc) {}
1157 /// \brief Called when the DFS steps back from a node.
1159 /// This function is called when the DFS steps back from a node.
1160 void leave(const Node& node) {}
1161 /// \brief Called when the DFS steps back on an arc.
1163 /// This function is called when the DFS steps back on an arc.
1164 void backtrack(const Arc& arc) {}
1167 template <typename _Digraph>
1169 typedef _Digraph Digraph;
1170 typedef typename Digraph::Arc Arc;
1171 typedef typename Digraph::Node Node;
1172 void start(const Node&) {}
1173 void stop(const Node&) {}
1174 void reach(const Node&) {}
1175 void discover(const Arc&) {}
1176 void examine(const Arc&) {}
1177 void leave(const Node&) {}
1178 void backtrack(const Arc&) {}
1180 template <typename _Visitor>
1181 struct Constraints {
1182 void constraints() {
1185 visitor.start(node);
1187 visitor.reach(node);
1188 visitor.discover(arc);
1189 visitor.examine(arc);
1190 visitor.leave(node);
1191 visitor.backtrack(arc);
1198 /// \brief Default traits class of DfsVisit class.
1200 /// Default traits class of DfsVisit class.
1201 /// \tparam _Digraph The type of the digraph the algorithm runs on.
1202 template<class _Digraph>
1203 struct DfsVisitDefaultTraits {
1205 /// \brief The type of the digraph the algorithm runs on.
1206 typedef _Digraph Digraph;
1208 /// \brief The type of the map that indicates which nodes are reached.
1210 /// The type of the map that indicates which nodes are reached.
1211 /// It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
1212 typedef typename Digraph::template NodeMap<bool> ReachedMap;
1214 /// \brief Instantiates a ReachedMap.
1216 /// This function instantiates a ReachedMap.
1217 /// \param digraph is the digraph, to which
1218 /// we would like to define the ReachedMap.
1219 static ReachedMap *createReachedMap(const Digraph &digraph) {
1220 return new ReachedMap(digraph);
1227 /// \brief %DFS algorithm class with visitor interface.
1229 /// This class provides an efficient implementation of the %DFS algorithm
1230 /// with visitor interface.
1232 /// The %DfsVisit class provides an alternative interface to the Dfs
1233 /// class. It works with callback mechanism, the DfsVisit object calls
1234 /// the member functions of the \c Visitor class on every DFS event.
1236 /// This interface of the DFS algorithm should be used in special cases
1237 /// when extra actions have to be performed in connection with certain
1238 /// events of the DFS algorithm. Otherwise consider to use Dfs or dfs()
1241 /// \tparam _Digraph The type of the digraph the algorithm runs on.
1242 /// The default value is
1243 /// \ref ListDigraph. The value of _Digraph is not used directly by
1244 /// \ref DfsVisit, it is only passed to \ref DfsVisitDefaultTraits.
1245 /// \tparam _Visitor The Visitor type that is used by the algorithm.
1246 /// \ref DfsVisitor "DfsVisitor<_Digraph>" is an empty visitor, which
1247 /// does not observe the DFS events. If you want to observe the DFS
1248 /// events, you should implement your own visitor class.
1249 /// \tparam _Traits Traits class to set various data types used by the
1250 /// algorithm. The default traits class is
1251 /// \ref DfsVisitDefaultTraits "DfsVisitDefaultTraits<_Digraph>".
1252 /// See \ref DfsVisitDefaultTraits for the documentation of
1253 /// a DFS visit traits class.
1255 template <typename _Digraph, typename _Visitor, typename _Traits>
1257 template <typename _Digraph = ListDigraph,
1258 typename _Visitor = DfsVisitor<_Digraph>,
1259 typename _Traits = DfsVisitDefaultTraits<_Digraph> >
1264 ///The traits class.
1265 typedef _Traits Traits;
1267 ///The type of the digraph the algorithm runs on.
1268 typedef typename Traits::Digraph Digraph;
1270 ///The visitor type used by the algorithm.
1271 typedef _Visitor Visitor;
1273 ///The type of the map that indicates which nodes are reached.
1274 typedef typename Traits::ReachedMap ReachedMap;
1278 typedef typename Digraph::Node Node;
1279 typedef typename Digraph::NodeIt NodeIt;
1280 typedef typename Digraph::Arc Arc;
1281 typedef typename Digraph::OutArcIt OutArcIt;
1283 //Pointer to the underlying digraph.
1284 const Digraph *_digraph;
1285 //Pointer to the visitor object.
1287 //Pointer to the map of reached status of the nodes.
1288 ReachedMap *_reached;
1289 //Indicates if _reached is locally allocated (true) or not.
1292 std::vector<typename Digraph::Arc> _stack;
1295 //Creates the maps if necessary.
1296 void create_maps() {
1298 local_reached = true;
1299 _reached = Traits::createReachedMap(*_digraph);
1309 typedef DfsVisit Create;
1311 /// \name Named Template Parameters
1315 struct SetReachedMapTraits : public Traits {
1316 typedef T ReachedMap;
1317 static ReachedMap *createReachedMap(const Digraph &digraph) {
1318 LEMON_ASSERT(false, "ReachedMap is not initialized");
1319 return 0; // ignore warnings
1322 /// \brief \ref named-templ-param "Named parameter" for setting
1323 /// ReachedMap type.
1325 /// \ref named-templ-param "Named parameter" for setting ReachedMap type.
1327 struct SetReachedMap : public DfsVisit< Digraph, Visitor,
1328 SetReachedMapTraits<T> > {
1329 typedef DfsVisit< Digraph, Visitor, SetReachedMapTraits<T> > Create;
1335 /// \brief Constructor.
1339 /// \param digraph The digraph the algorithm runs on.
1340 /// \param visitor The visitor object of the algorithm.
1341 DfsVisit(const Digraph& digraph, Visitor& visitor)
1342 : _digraph(&digraph), _visitor(&visitor),
1343 _reached(0), local_reached(false) {}
1345 /// \brief Destructor.
1347 if(local_reached) delete _reached;
1350 /// \brief Sets the map that indicates which nodes are reached.
1352 /// Sets the map that indicates which nodes are reached.
1353 /// If you don't use this function before calling \ref run(Node) "run()"
1354 /// or \ref init(), an instance will be allocated automatically.
1355 /// The destructor deallocates this automatically allocated map,
1357 /// \return <tt> (*this) </tt>
1358 DfsVisit &reachedMap(ReachedMap &m) {
1361 local_reached=false;
1369 /// \name Execution Control
1370 /// The simplest way to execute the DFS algorithm is to use one of the
1371 /// member functions called \ref run(Node) "run()".\n
1372 /// If you need more control on the execution, first you have to call
1373 /// \ref init(), then you can add a source node with \ref addSource()
1374 /// and perform the actual computation with \ref start().
1375 /// This procedure can be repeated if there are nodes that have not
1380 /// \brief Initializes the internal data structures.
1382 /// Initializes the internal data structures.
1385 _stack.resize(countNodes(*_digraph));
1387 for (NodeIt u(*_digraph) ; u != INVALID ; ++u) {
1388 _reached->set(u, false);
1392 /// \brief Adds a new source node.
1394 /// Adds a new source node to the set of nodes to be processed.
1396 /// \pre The stack must be empty. Otherwise the algorithm gives
1397 /// wrong results. (One of the outgoing arcs of all the source nodes
1398 /// except for the last one will not be visited and distances will
1400 void addSource(Node s)
1402 LEMON_DEBUG(emptyQueue(), "The stack is not empty.");
1403 if(!(*_reached)[s]) {
1404 _reached->set(s,true);
1408 _digraph->firstOut(e, s);
1410 _stack[++_stack_head] = e;
1418 /// \brief Processes the next arc.
1420 /// Processes the next arc.
1422 /// \return The processed arc.
1424 /// \pre The stack must not be empty.
1425 Arc processNextArc() {
1426 Arc e = _stack[_stack_head];
1427 Node m = _digraph->target(e);
1428 if(!(*_reached)[m]) {
1429 _visitor->discover(e);
1431 _reached->set(m, true);
1432 _digraph->firstOut(_stack[++_stack_head], m);
1434 _visitor->examine(e);
1435 m = _digraph->source(e);
1436 _digraph->nextOut(_stack[_stack_head]);
1438 while (_stack_head>=0 && _stack[_stack_head] == INVALID) {
1441 if (_stack_head >= 0) {
1442 _visitor->backtrack(_stack[_stack_head]);
1443 m = _digraph->source(_stack[_stack_head]);
1444 _digraph->nextOut(_stack[_stack_head]);
1452 /// \brief Next arc to be processed.
1454 /// Next arc to be processed.
1456 /// \return The next arc to be processed or INVALID if the stack is
1458 Arc nextArc() const {
1459 return _stack_head >= 0 ? _stack[_stack_head] : INVALID;
1462 /// \brief Returns \c false if there are nodes
1463 /// to be processed.
1465 /// Returns \c false if there are nodes
1466 /// to be processed in the queue (stack).
1467 bool emptyQueue() const { return _stack_head < 0; }
1469 /// \brief Returns the number of the nodes to be processed.
1471 /// Returns the number of the nodes to be processed in the queue (stack).
1472 int queueSize() const { return _stack_head + 1; }
1474 /// \brief Executes the algorithm.
1476 /// Executes the algorithm.
1478 /// This method runs the %DFS algorithm from the root node
1479 /// in order to compute the %DFS path to each node.
1481 /// The algorithm computes
1482 /// - the %DFS tree,
1483 /// - the distance of each node from the root in the %DFS tree.
1485 /// \pre init() must be called and a root node should be
1486 /// added with addSource() before using this function.
1488 /// \note <tt>d.start()</tt> is just a shortcut of the following code.
1490 /// while ( !d.emptyQueue() ) {
1491 /// d.processNextArc();
1495 while ( !emptyQueue() ) processNextArc();
1498 /// \brief Executes the algorithm until the given target node is reached.
1500 /// Executes the algorithm until the given target node is reached.
1502 /// This method runs the %DFS algorithm from the root node
1503 /// in order to compute the DFS path to \c t.
1505 /// The algorithm computes
1506 /// - the %DFS path to \c t,
1507 /// - the distance of \c t from the root in the %DFS tree.
1509 /// \pre init() must be called and a root node should be added
1510 /// with addSource() before using this function.
1511 void start(Node t) {
1512 while ( !emptyQueue() && _digraph->target(_stack[_stack_head]) != t )
1516 /// \brief Executes the algorithm until a condition is met.
1518 /// Executes the algorithm until a condition is met.
1520 /// This method runs the %DFS algorithm from the root node
1521 /// until an arc \c a with <tt>am[a]</tt> true is found.
1523 /// \param am A \c bool (or convertible) arc map. The algorithm
1524 /// will stop when it reaches an arc \c a with <tt>am[a]</tt> true.
1526 /// \return The reached arc \c a with <tt>am[a]</tt> true or
1527 /// \c INVALID if no such arc was found.
1529 /// \pre init() must be called and a root node should be added
1530 /// with addSource() before using this function.
1532 /// \warning Contrary to \ref Bfs and \ref Dijkstra, \c am is an arc map,
1534 template <typename AM>
1535 Arc start(const AM &am) {
1536 while ( !emptyQueue() && !am[_stack[_stack_head]] )
1538 return emptyQueue() ? INVALID : _stack[_stack_head];
1541 /// \brief Runs the algorithm from the given source node.
1543 /// This method runs the %DFS algorithm from node \c s.
1544 /// in order to compute the DFS path to each node.
1546 /// The algorithm computes
1547 /// - the %DFS tree,
1548 /// - the distance of each node from the root in the %DFS tree.
1550 /// \note <tt>d.run(s)</tt> is just a shortcut of the following code.
1562 /// \brief Finds the %DFS path between \c s and \c t.
1564 /// This method runs the %DFS algorithm from node \c s
1565 /// in order to compute the DFS path to node \c t
1566 /// (it stops searching when \c t is processed).
1568 /// \return \c true if \c t is reachable form \c s.
1570 /// \note Apart from the return value, <tt>d.run(s,t)</tt> is
1571 /// just a shortcut of the following code.
1577 bool run(Node s,Node t) {
1584 /// \brief Runs the algorithm to visit all nodes in the digraph.
1586 /// This method runs the %DFS algorithm in order to
1587 /// compute the %DFS path to each node.
1589 /// The algorithm computes
1590 /// - the %DFS tree (forest),
1591 /// - the distance of each node from the root(s) in the %DFS tree.
1593 /// \note <tt>d.run()</tt> is just a shortcut of the following code.
1596 /// for (NodeIt n(digraph); n != INVALID; ++n) {
1597 /// if (!d.reached(n)) {
1605 for (NodeIt it(*_digraph); it != INVALID; ++it) {
1615 /// \name Query Functions
1616 /// The results of the DFS algorithm can be obtained using these
1618 /// Either \ref run(Node) "run()" or \ref start() should be called
1619 /// before using them.
1623 /// \brief Checks if a node is reached from the root(s).
1625 /// Returns \c true if \c v is reached from the root(s).
1627 /// \pre Either \ref run(Node) "run()" or \ref init()
1628 /// must be called before using this function.
1629 bool reached(Node v) const { return (*_reached)[v]; }
1635 } //END OF NAMESPACE LEMON