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>
32 #include <lemon/path.h>
36 ///Default traits class of Dfs class.
38 ///Default traits class of Dfs class.
39 ///\tparam GR Digraph type.
41 struct DfsDefaultTraits
43 ///The type of the digraph the algorithm runs on.
46 ///\brief The type of the map that stores the predecessor
47 ///arcs of the %DFS paths.
49 ///The type of the map that stores the predecessor
50 ///arcs of the %DFS paths.
51 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
52 typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
53 ///Instantiates a \ref PredMap.
55 ///This function instantiates a \ref PredMap.
56 ///\param g is the digraph, to which we would like to define the
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 typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
68 ///Instantiates a \ref ProcessedMap.
70 ///This function instantiates a \ref ProcessedMap.
71 ///\param g is the digraph, to which
72 ///we would like to define the \ref ProcessedMap
74 static ProcessedMap *createProcessedMap(const Digraph &g)
76 static ProcessedMap *createProcessedMap(const Digraph &)
79 return new ProcessedMap();
82 ///The type of the map that indicates which nodes are reached.
84 ///The type of the map that indicates which nodes are reached.
85 ///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
86 typedef typename Digraph::template NodeMap<bool> ReachedMap;
87 ///Instantiates a \ref ReachedMap.
89 ///This function instantiates a \ref ReachedMap.
90 ///\param g is the digraph, to which
91 ///we would like to define the \ref ReachedMap.
92 static ReachedMap *createReachedMap(const Digraph &g)
94 return new ReachedMap(g);
97 ///The type of the map that stores the distances of the nodes.
99 ///The type of the map that stores the distances of the nodes.
100 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
101 typedef typename Digraph::template NodeMap<int> DistMap;
102 ///Instantiates a \ref DistMap.
104 ///This function instantiates a \ref DistMap.
105 ///\param g is the digraph, to which we would like to define the
107 static DistMap *createDistMap(const Digraph &g)
109 return new DistMap(g);
113 ///%DFS algorithm class.
116 ///This class provides an efficient implementation of the %DFS algorithm.
118 ///There is also a \ref dfs() "function-type interface" for the DFS
119 ///algorithm, which is convenient in the simplier cases and it can be
122 ///\tparam GR The type of the digraph the algorithm runs on.
123 ///The default value is \ref ListDigraph. The value of GR is not used
124 ///directly by \ref Dfs, it is only passed to \ref DfsDefaultTraits.
125 ///\tparam TR Traits class to set various data types used by the algorithm.
126 ///The default traits class is
127 ///\ref DfsDefaultTraits "DfsDefaultTraits<GR>".
128 ///See \ref DfsDefaultTraits for the documentation of
129 ///a Dfs traits class.
131 template <typename GR,
134 template <typename GR=ListDigraph,
135 typename TR=DfsDefaultTraits<GR> >
140 ///The type of the digraph the algorithm runs on.
141 typedef typename TR::Digraph Digraph;
143 ///\brief The type of the map that stores the predecessor arcs of the
145 typedef typename TR::PredMap PredMap;
146 ///The type of the map that stores the distances of the nodes.
147 typedef typename TR::DistMap DistMap;
148 ///The type of the map that indicates which nodes are reached.
149 typedef typename TR::ReachedMap ReachedMap;
150 ///The type of the map that indicates which nodes are processed.
151 typedef typename TR::ProcessedMap ProcessedMap;
152 ///The type of the paths.
153 typedef PredMapPath<Digraph, PredMap> Path;
160 typedef typename Digraph::Node Node;
161 typedef typename Digraph::NodeIt NodeIt;
162 typedef typename Digraph::Arc Arc;
163 typedef typename Digraph::OutArcIt OutArcIt;
165 //Pointer to the underlying digraph.
167 //Pointer to the map of predecessor arcs.
169 //Indicates if _pred is locally allocated (true) or not.
171 //Pointer to the map of distances.
173 //Indicates if _dist is locally allocated (true) or not.
175 //Pointer to the map of reached status of the nodes.
176 ReachedMap *_reached;
177 //Indicates if _reached is locally allocated (true) or not.
179 //Pointer to the map of processed status of the nodes.
180 ProcessedMap *_processed;
181 //Indicates if _processed is locally allocated (true) or not.
182 bool local_processed;
184 std::vector<typename Digraph::OutArcIt> _stack;
187 //Creates the maps if necessary.
192 _pred = Traits::createPredMap(*G);
196 _dist = Traits::createDistMap(*G);
199 local_reached = true;
200 _reached = Traits::createReachedMap(*G);
203 local_processed = true;
204 _processed = Traits::createProcessedMap(*G);
216 ///\name Named template parameters
221 struct SetPredMapTraits : public Traits {
223 static PredMap *createPredMap(const Digraph &)
225 LEMON_ASSERT(false, "PredMap is not initialized");
226 return 0; // ignore warnings
229 ///\brief \ref named-templ-param "Named parameter" for setting
230 ///\ref PredMap type.
232 ///\ref named-templ-param "Named parameter" for setting
233 ///\ref PredMap type.
235 struct SetPredMap : public Dfs<Digraph, SetPredMapTraits<T> > {
236 typedef Dfs<Digraph, SetPredMapTraits<T> > Create;
240 struct SetDistMapTraits : public Traits {
242 static DistMap *createDistMap(const Digraph &)
244 LEMON_ASSERT(false, "DistMap is not initialized");
245 return 0; // ignore warnings
248 ///\brief \ref named-templ-param "Named parameter" for setting
249 ///\ref DistMap type.
251 ///\ref named-templ-param "Named parameter" for setting
252 ///\ref DistMap type.
254 struct SetDistMap : public Dfs< Digraph, SetDistMapTraits<T> > {
255 typedef Dfs<Digraph, SetDistMapTraits<T> > Create;
259 struct SetReachedMapTraits : public Traits {
260 typedef T ReachedMap;
261 static ReachedMap *createReachedMap(const Digraph &)
263 LEMON_ASSERT(false, "ReachedMap is not initialized");
264 return 0; // ignore warnings
267 ///\brief \ref named-templ-param "Named parameter" for setting
268 ///\ref ReachedMap type.
270 ///\ref named-templ-param "Named parameter" for setting
271 ///\ref ReachedMap type.
273 struct SetReachedMap : public Dfs< Digraph, SetReachedMapTraits<T> > {
274 typedef Dfs< Digraph, SetReachedMapTraits<T> > Create;
278 struct SetProcessedMapTraits : public Traits {
279 typedef T ProcessedMap;
280 static ProcessedMap *createProcessedMap(const Digraph &)
282 LEMON_ASSERT(false, "ProcessedMap is not initialized");
283 return 0; // ignore warnings
286 ///\brief \ref named-templ-param "Named parameter" for setting
287 ///\ref ProcessedMap type.
289 ///\ref named-templ-param "Named parameter" for setting
290 ///\ref ProcessedMap type.
292 struct SetProcessedMap : public Dfs< Digraph, SetProcessedMapTraits<T> > {
293 typedef Dfs< Digraph, SetProcessedMapTraits<T> > Create;
296 struct SetStandardProcessedMapTraits : public Traits {
297 typedef typename Digraph::template NodeMap<bool> ProcessedMap;
298 static ProcessedMap *createProcessedMap(const Digraph &g)
300 return new ProcessedMap(g);
303 ///\brief \ref named-templ-param "Named parameter" for setting
304 ///\ref ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
306 ///\ref named-templ-param "Named parameter" for setting
307 ///\ref ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
308 ///If you don't set it explicitly, it will be automatically allocated.
309 struct SetStandardProcessedMap :
310 public Dfs< Digraph, SetStandardProcessedMapTraits > {
311 typedef Dfs< Digraph, SetStandardProcessedMapTraits > Create;
321 ///\param g The digraph the algorithm runs on.
322 Dfs(const Digraph &g) :
324 _pred(NULL), local_pred(false),
325 _dist(NULL), local_dist(false),
326 _reached(NULL), local_reached(false),
327 _processed(NULL), local_processed(false)
333 if(local_pred) delete _pred;
334 if(local_dist) delete _dist;
335 if(local_reached) delete _reached;
336 if(local_processed) delete _processed;
339 ///Sets the map that stores the predecessor arcs.
341 ///Sets the map that stores the predecessor arcs.
342 ///If you don't use this function before calling \ref run(),
343 ///it will allocate one. The destructor deallocates this
344 ///automatically allocated map, of course.
345 ///\return <tt> (*this) </tt>
346 Dfs &predMap(PredMap &m)
356 ///Sets the map that indicates which nodes are reached.
358 ///Sets the map that indicates which nodes are reached.
359 ///If you don't use this function before calling \ref run(),
360 ///it will allocate one. The destructor deallocates this
361 ///automatically allocated map, of course.
362 ///\return <tt> (*this) </tt>
363 Dfs &reachedMap(ReachedMap &m)
373 ///Sets the map that indicates which nodes are processed.
375 ///Sets the map that indicates which nodes are processed.
376 ///If you don't use this function before calling \ref run(),
377 ///it will allocate one. The destructor deallocates this
378 ///automatically allocated map, of course.
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(),
395 ///it will allocate one. The destructor deallocates this
396 ///automatically allocated map, of course.
397 ///\return <tt> (*this) </tt>
398 Dfs &distMap(DistMap &m)
410 ///\name Execution control
411 ///The simplest way to execute the algorithm is to use
412 ///one of the member functions called \ref lemon::Dfs::run() "run()".
414 ///If you need more control on the execution, first you must call
415 ///\ref lemon::Dfs::init() "init()", then you can add a source node
416 ///with \ref lemon::Dfs::addSource() "addSource()".
417 ///Finally \ref lemon::Dfs::start() "start()" will perform the
418 ///actual path computation.
422 ///Initializes the internal data structures.
424 ///Initializes the internal data structures.
429 _stack.resize(countNodes(*G));
431 for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
432 _pred->set(u,INVALID);
433 _reached->set(u,false);
434 _processed->set(u,false);
438 ///Adds a new source node.
440 ///Adds a new source node to the set of nodes to be processed.
442 ///\pre The stack must be empty. (Otherwise the algorithm gives
445 ///\warning Distances will be wrong (or at least strange) in case of
447 void addSource(Node s)
449 LEMON_DEBUG(emptyQueue(), "The stack is not empty.");
452 _reached->set(s,true);
453 _pred->set(s,INVALID);
456 _stack[++_stack_head]=e;
457 _dist->set(s,_stack_head);
460 _processed->set(s,true);
466 ///Processes the next arc.
468 ///Processes the next arc.
470 ///\return The processed arc.
472 ///\pre The stack must not be empty.
476 Arc e=_stack[_stack_head];
477 if(!(*_reached)[m=G->target(e)]) {
479 _reached->set(m,true);
481 _stack[_stack_head] = OutArcIt(*G, m);
482 _dist->set(m,_stack_head);
486 ++_stack[_stack_head];
488 while(_stack_head>=0 && _stack[_stack_head]==INVALID) {
489 _processed->set(m,true);
492 m=G->source(_stack[_stack_head]);
493 ++_stack[_stack_head];
499 ///Next arc to be processed.
501 ///Next arc to be processed.
503 ///\return The next arc to be processed or \c INVALID if the stack
505 OutArcIt nextArc() const
507 return _stack_head>=0?_stack[_stack_head]:INVALID;
510 ///\brief Returns \c false if there are nodes
513 ///Returns \c false if there are nodes
514 ///to be processed in the queue (stack).
515 bool emptyQueue() const { return _stack_head<0; }
517 ///Returns the number of the nodes to be processed.
519 ///Returns the number of the nodes to be processed in the queue (stack).
520 int queueSize() const { return _stack_head+1; }
522 ///Executes the algorithm.
524 ///Executes the algorithm.
526 ///This method runs the %DFS algorithm from the root node
527 ///in order to compute the DFS path to each node.
529 /// The algorithm computes
531 ///- the distance of each node from the root in the %DFS tree.
533 ///\pre init() must be called and a root node should be
534 ///added with addSource() before using this function.
536 ///\note <tt>d.start()</tt> is just a shortcut of the following code.
538 /// while ( !d.emptyQueue() ) {
539 /// d.processNextArc();
544 while ( !emptyQueue() ) processNextArc();
547 ///Executes the algorithm until the given target node is reached.
549 ///Executes the algorithm until the given target node is reached.
551 ///This method runs the %DFS algorithm from the root node
552 ///in order to compute the DFS path to \c t.
554 ///The algorithm computes
555 ///- the %DFS path to \c t,
556 ///- the distance of \c t from the root in the %DFS tree.
558 ///\pre init() must be called and a root node should be
559 ///added with addSource() before using this function.
562 while ( !emptyQueue() && G->target(_stack[_stack_head])!=t )
566 ///Executes the algorithm until a condition is met.
568 ///Executes the algorithm until a condition is met.
570 ///This method runs the %DFS algorithm from the root node
571 ///until an arc \c a with <tt>am[a]</tt> true is found.
573 ///\param am A \c bool (or convertible) arc map. The algorithm
574 ///will stop when it reaches an arc \c a with <tt>am[a]</tt> true.
576 ///\return The reached arc \c a with <tt>am[a]</tt> true or
577 ///\c INVALID if no such arc was found.
579 ///\pre init() must be called and a root node should be
580 ///added with addSource() before using this function.
582 ///\warning Contrary to \ref Bfs and \ref Dijkstra, \c am is an arc map,
584 template<class ArcBoolMap>
585 Arc start(const ArcBoolMap &am)
587 while ( !emptyQueue() && !am[_stack[_stack_head]] )
589 return emptyQueue() ? INVALID : _stack[_stack_head];
592 ///Runs the algorithm from the given source node.
594 ///This method runs the %DFS algorithm from node \c s
595 ///in order to compute the DFS path to each node.
597 ///The algorithm computes
599 ///- the distance of each node from the root in the %DFS tree.
601 ///\note <tt>d.run(s)</tt> is just a shortcut of the following code.
613 ///Finds the %DFS path between \c s and \c t.
615 ///This method runs the %DFS algorithm from node \c s
616 ///in order to compute the DFS path to node \c t
617 ///(it stops searching when \c t is processed)
619 ///\return \c true if \c t is reachable form \c s.
621 ///\note Apart from the return value, <tt>d.run(s,t)</tt> is
622 ///just a shortcut of the following code.
628 bool run(Node s,Node t) {
635 ///Runs the algorithm to visit all nodes in the digraph.
637 ///This method runs the %DFS algorithm in order to compute the
638 ///%DFS path to each node.
640 ///The algorithm computes
642 ///- the distance of each node from the root in the %DFS tree.
644 ///\note <tt>d.run()</tt> is just a shortcut of the following code.
647 /// for (NodeIt n(digraph); n != INVALID; ++n) {
648 /// if (!d.reached(n)) {
656 for (NodeIt it(*G); it != INVALID; ++it) {
666 ///\name Query Functions
667 ///The result of the %DFS algorithm can be obtained using these
669 ///Either \ref lemon::Dfs::run() "run()" or \ref lemon::Dfs::start()
670 ///"start()" must be called before using them.
674 ///The DFS path to a node.
676 ///Returns the DFS path to a node.
678 ///\warning \c t should be reachable from the root.
680 ///\pre Either \ref run() or \ref start() must be called before
681 ///using this function.
682 Path path(Node t) const { return Path(*G, *_pred, t); }
684 ///The distance of a node from the root.
686 ///Returns the distance of a node from the root.
688 ///\warning If node \c v is not reachable from the root, then
689 ///the return value of this function is undefined.
691 ///\pre Either \ref run() or \ref start() must be called before
692 ///using this function.
693 int dist(Node v) const { return (*_dist)[v]; }
695 ///Returns the 'previous arc' of the %DFS tree for a node.
697 ///This function returns the 'previous arc' of the %DFS tree for the
698 ///node \c v, i.e. it returns the last arc of a %DFS path from the
699 ///root to \c v. It is \c INVALID
700 ///if \c v is not reachable from the root(s) or if \c v is a root.
702 ///The %DFS tree used here is equal to the %DFS tree used in
705 ///\pre Either \ref run() or \ref start() must be called before using
707 Arc predArc(Node v) const { return (*_pred)[v];}
709 ///Returns the 'previous node' of the %DFS tree.
711 ///This function returns the 'previous node' of the %DFS
712 ///tree for the node \c v, i.e. it returns the last but one node
713 ///from a %DFS path from the root to \c v. It is \c INVALID
714 ///if \c v is not reachable from the root(s) or if \c v is a root.
716 ///The %DFS tree used here is equal to the %DFS tree used in
719 ///\pre Either \ref run() or \ref start() must be called before
720 ///using this function.
721 Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
722 G->source((*_pred)[v]); }
724 ///\brief Returns a const reference to the node map that stores the
725 ///distances of the nodes.
727 ///Returns a const reference to the node map that stores the
728 ///distances of the nodes calculated by the algorithm.
730 ///\pre Either \ref run() or \ref init()
731 ///must be called before using this function.
732 const DistMap &distMap() const { return *_dist;}
734 ///\brief Returns a const reference to the node map that stores the
737 ///Returns a const reference to the node map that stores the predecessor
738 ///arcs, which form the DFS tree.
740 ///\pre Either \ref run() or \ref init()
741 ///must be called before using this function.
742 const PredMap &predMap() const { return *_pred;}
744 ///Checks if a node is reachable from the root(s).
746 ///Returns \c true if \c v is reachable from the root(s).
747 ///\pre Either \ref run() or \ref start()
748 ///must be called before using this function.
749 bool reached(Node v) const { return (*_reached)[v]; }
754 ///Default traits class of dfs() function.
756 ///Default traits class of dfs() function.
757 ///\tparam GR Digraph type.
759 struct DfsWizardDefaultTraits
761 ///The type of the digraph the algorithm runs on.
764 ///\brief The type of the map that stores the predecessor
765 ///arcs of the %DFS paths.
767 ///The type of the map that stores the predecessor
768 ///arcs of the %DFS paths.
769 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
770 typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
771 ///Instantiates a \ref PredMap.
773 ///This function instantiates a \ref PredMap.
774 ///\param g is the digraph, to which we would like to define the
776 static PredMap *createPredMap(const Digraph &g)
778 return new PredMap(g);
781 ///The type of the map that indicates which nodes are processed.
783 ///The type of the map that indicates which nodes are processed.
784 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
785 ///By default it is a NullMap.
786 typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
787 ///Instantiates a \ref ProcessedMap.
789 ///This function instantiates a \ref ProcessedMap.
790 ///\param g is the digraph, to which
791 ///we would like to define the \ref ProcessedMap.
793 static ProcessedMap *createProcessedMap(const Digraph &g)
795 static ProcessedMap *createProcessedMap(const Digraph &)
798 return new ProcessedMap();
801 ///The type of the map that indicates which nodes are reached.
803 ///The type of the map that indicates which nodes are reached.
804 ///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
805 typedef typename Digraph::template NodeMap<bool> ReachedMap;
806 ///Instantiates a \ref ReachedMap.
808 ///This function instantiates a \ref ReachedMap.
809 ///\param g is the digraph, to which
810 ///we would like to define the \ref ReachedMap.
811 static ReachedMap *createReachedMap(const Digraph &g)
813 return new ReachedMap(g);
816 ///The type of the map that stores the distances of the nodes.
818 ///The type of the map that stores the distances of the nodes.
819 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
820 typedef typename Digraph::template NodeMap<int> DistMap;
821 ///Instantiates a \ref DistMap.
823 ///This function instantiates a \ref DistMap.
824 ///\param g is the digraph, to which we would like to define
826 static DistMap *createDistMap(const Digraph &g)
828 return new DistMap(g);
831 ///The type of the DFS paths.
833 ///The type of the DFS paths.
834 ///It must meet the \ref concepts::Path "Path" concept.
835 typedef lemon::Path<Digraph> Path;
838 /// Default traits class used by \ref DfsWizard
840 /// To make it easier to use Dfs algorithm
841 /// we have created a wizard class.
842 /// This \ref DfsWizard class needs default traits,
843 /// as well as the \ref Dfs class.
844 /// The \ref DfsWizardBase is a class to be the default traits of the
845 /// \ref DfsWizard class.
847 class DfsWizardBase : public DfsWizardDefaultTraits<GR>
850 typedef DfsWizardDefaultTraits<GR> Base;
852 //The type of the nodes in the digraph.
853 typedef typename Base::Digraph::Node Node;
855 //Pointer to the digraph the algorithm runs on.
857 //Pointer to the map of reached nodes.
859 //Pointer to the map of processed nodes.
861 //Pointer to the map of predecessors arcs.
863 //Pointer to the map of distances.
865 //Pointer to the DFS path to the target node.
867 //Pointer to the distance of the target node.
873 /// This constructor does not require parameters, therefore it initiates
874 /// all of the attributes to \c 0.
875 DfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0),
876 _dist(0), _path(0), _di(0) {}
880 /// This constructor requires one parameter,
881 /// others are initiated to \c 0.
882 /// \param g The digraph the algorithm runs on.
883 DfsWizardBase(const GR &g) :
884 _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
885 _reached(0), _processed(0), _pred(0), _dist(0), _path(0), _di(0) {}
889 /// Auxiliary class for the function-type interface of DFS algorithm.
891 /// This auxiliary class is created to implement the
892 /// \ref dfs() "function-type interface" of \ref Dfs algorithm.
893 /// It does not have own \ref run() method, it uses the functions
894 /// and features of the plain \ref Dfs.
896 /// This class should only be used through the \ref dfs() function,
897 /// which makes it easier to use the algorithm.
899 class DfsWizard : public TR
903 ///The type of the digraph the algorithm runs on.
904 typedef typename TR::Digraph Digraph;
906 typedef typename Digraph::Node Node;
907 typedef typename Digraph::NodeIt NodeIt;
908 typedef typename Digraph::Arc Arc;
909 typedef typename Digraph::OutArcIt OutArcIt;
911 ///\brief The type of the map that stores the predecessor
912 ///arcs of the DFS paths.
913 typedef typename TR::PredMap PredMap;
914 ///\brief The type of the map that stores the distances of the nodes.
915 typedef typename TR::DistMap DistMap;
916 ///\brief The type of the map that indicates which nodes are reached.
917 typedef typename TR::ReachedMap ReachedMap;
918 ///\brief The type of the map that indicates which nodes are processed.
919 typedef typename TR::ProcessedMap ProcessedMap;
920 ///The type of the DFS paths
921 typedef typename TR::Path Path;
926 DfsWizard() : TR() {}
928 /// Constructor that requires parameters.
930 /// Constructor that requires parameters.
931 /// These parameters will be the default values for the traits class.
932 /// \param g The digraph the algorithm runs on.
933 DfsWizard(const Digraph &g) :
937 DfsWizard(const TR &b) : TR(b) {}
941 ///Runs DFS algorithm from the given source node.
943 ///This method runs DFS algorithm from node \c s
944 ///in order to compute the DFS path to each node.
947 Dfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
949 alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
951 alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
953 alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
954 if (Base::_processed)
955 alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
962 ///Finds the DFS path between \c s and \c t.
964 ///This method runs DFS algorithm from node \c s
965 ///in order to compute the DFS path to node \c t
966 ///(it stops searching when \c t is processed).
968 ///\return \c true if \c t is reachable form \c s.
969 bool run(Node s, Node t)
971 Dfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
973 alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
975 alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
977 alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
978 if (Base::_processed)
979 alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
982 *reinterpret_cast<Path*>(Base::_path) = alg.path(t);
984 *Base::_di = alg.dist(t);
985 return alg.reached(t);
988 ///Runs DFS algorithm to visit all nodes in the digraph.
990 ///This method runs DFS algorithm in order to compute
991 ///the DFS path to each node.
998 struct SetPredMapBase : public Base {
1000 static PredMap *createPredMap(const Digraph &) { return 0; };
1001 SetPredMapBase(const TR &b) : TR(b) {}
1003 ///\brief \ref named-func-param "Named parameter"
1004 ///for setting \ref PredMap object.
1006 ///\ref named-func-param "Named parameter"
1007 ///for setting \ref PredMap object.
1009 DfsWizard<SetPredMapBase<T> > predMap(const T &t)
1011 Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1012 return DfsWizard<SetPredMapBase<T> >(*this);
1016 struct SetReachedMapBase : public Base {
1017 typedef T ReachedMap;
1018 static ReachedMap *createReachedMap(const Digraph &) { return 0; };
1019 SetReachedMapBase(const TR &b) : TR(b) {}
1021 ///\brief \ref named-func-param "Named parameter"
1022 ///for setting \ref ReachedMap object.
1024 /// \ref named-func-param "Named parameter"
1025 ///for setting \ref ReachedMap object.
1027 DfsWizard<SetReachedMapBase<T> > reachedMap(const T &t)
1029 Base::_reached=reinterpret_cast<void*>(const_cast<T*>(&t));
1030 return DfsWizard<SetReachedMapBase<T> >(*this);
1034 struct SetDistMapBase : public Base {
1036 static DistMap *createDistMap(const Digraph &) { return 0; };
1037 SetDistMapBase(const TR &b) : TR(b) {}
1039 ///\brief \ref named-func-param "Named parameter"
1040 ///for setting \ref DistMap object.
1042 /// \ref named-func-param "Named parameter"
1043 ///for setting \ref DistMap object.
1045 DfsWizard<SetDistMapBase<T> > distMap(const T &t)
1047 Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1048 return DfsWizard<SetDistMapBase<T> >(*this);
1052 struct SetProcessedMapBase : public Base {
1053 typedef T ProcessedMap;
1054 static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
1055 SetProcessedMapBase(const TR &b) : TR(b) {}
1057 ///\brief \ref named-func-param "Named parameter"
1058 ///for setting \ref ProcessedMap object.
1060 /// \ref named-func-param "Named parameter"
1061 ///for setting \ref ProcessedMap object.
1063 DfsWizard<SetProcessedMapBase<T> > processedMap(const T &t)
1065 Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1066 return DfsWizard<SetProcessedMapBase<T> >(*this);
1070 struct SetPathBase : public Base {
1072 SetPathBase(const TR &b) : TR(b) {}
1074 ///\brief \ref named-func-param "Named parameter"
1075 ///for getting the DFS path to the target node.
1077 ///\ref named-func-param "Named parameter"
1078 ///for getting the DFS path to the target node.
1080 DfsWizard<SetPathBase<T> > path(const T &t)
1082 Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t));
1083 return DfsWizard<SetPathBase<T> >(*this);
1086 ///\brief \ref named-func-param "Named parameter"
1087 ///for getting the distance of the target node.
1089 ///\ref named-func-param "Named parameter"
1090 ///for getting the distance of the target node.
1091 DfsWizard dist(const int &d)
1093 Base::_di=const_cast<int*>(&d);
1099 ///Function-type interface for DFS algorithm.
1102 ///Function-type interface for DFS algorithm.
1104 ///This function also has several \ref named-func-param "named parameters",
1105 ///they are declared as the members of class \ref DfsWizard.
1106 ///The following examples show how to use these parameters.
1108 /// // Compute the DFS tree
1109 /// dfs(g).predMap(preds).distMap(dists).run(s);
1111 /// // Compute the DFS path from s to t
1112 /// bool reached = dfs(g).path(p).dist(d).run(s,t);
1115 ///\warning Don't forget to put the \ref DfsWizard::run() "run()"
1116 ///to the end of the parameter list.
1120 DfsWizard<DfsWizardBase<GR> >
1121 dfs(const GR &digraph)
1123 return DfsWizard<DfsWizardBase<GR> >(digraph);
1127 /// \brief Visitor class for DFS.
1129 /// This class defines the interface of the DfsVisit events, and
1130 /// it could be the base of a real visitor class.
1131 template <typename _Digraph>
1133 typedef _Digraph Digraph;
1134 typedef typename Digraph::Arc Arc;
1135 typedef typename Digraph::Node Node;
1136 /// \brief Called for the source node of the DFS.
1138 /// This function is called for the source node of the DFS.
1139 void start(const Node& node) {}
1140 /// \brief Called when the source node is leaved.
1142 /// This function is called when the source node is leaved.
1143 void stop(const Node& node) {}
1144 /// \brief Called when a node is reached first time.
1146 /// This function is called when a node is reached first time.
1147 void reach(const Node& node) {}
1148 /// \brief Called when an arc reaches a new node.
1150 /// This function is called when the DFS finds an arc whose target node
1151 /// is not reached yet.
1152 void discover(const Arc& arc) {}
1153 /// \brief Called when an arc is examined but its target node is
1154 /// already discovered.
1156 /// This function is called when an arc is examined but its target node is
1157 /// already discovered.
1158 void examine(const Arc& arc) {}
1159 /// \brief Called when the DFS steps back from a node.
1161 /// This function is called when the DFS steps back from a node.
1162 void leave(const Node& node) {}
1163 /// \brief Called when the DFS steps back on an arc.
1165 /// This function is called when the DFS steps back on an arc.
1166 void backtrack(const Arc& arc) {}
1169 template <typename _Digraph>
1171 typedef _Digraph Digraph;
1172 typedef typename Digraph::Arc Arc;
1173 typedef typename Digraph::Node Node;
1174 void start(const Node&) {}
1175 void stop(const Node&) {}
1176 void reach(const Node&) {}
1177 void discover(const Arc&) {}
1178 void examine(const Arc&) {}
1179 void leave(const Node&) {}
1180 void backtrack(const Arc&) {}
1182 template <typename _Visitor>
1183 struct Constraints {
1184 void constraints() {
1187 visitor.start(node);
1189 visitor.reach(node);
1190 visitor.discover(arc);
1191 visitor.examine(arc);
1192 visitor.leave(node);
1193 visitor.backtrack(arc);
1200 /// \brief Default traits class of DfsVisit class.
1202 /// Default traits class of DfsVisit class.
1203 /// \tparam _Digraph The type of the digraph the algorithm runs on.
1204 template<class _Digraph>
1205 struct DfsVisitDefaultTraits {
1207 /// \brief The type of the digraph the algorithm runs on.
1208 typedef _Digraph Digraph;
1210 /// \brief The type of the map that indicates which nodes are reached.
1212 /// The type of the map that indicates which nodes are reached.
1213 /// It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
1214 typedef typename Digraph::template NodeMap<bool> ReachedMap;
1216 /// \brief Instantiates a \ref ReachedMap.
1218 /// This function instantiates a \ref ReachedMap.
1219 /// \param digraph is the digraph, to which
1220 /// we would like to define the \ref ReachedMap.
1221 static ReachedMap *createReachedMap(const Digraph &digraph) {
1222 return new ReachedMap(digraph);
1229 /// \brief %DFS algorithm class with visitor interface.
1231 /// This class provides an efficient implementation of the %DFS algorithm
1232 /// with visitor interface.
1234 /// The %DfsVisit class provides an alternative interface to the Dfs
1235 /// class. It works with callback mechanism, the DfsVisit object calls
1236 /// the member functions of the \c Visitor class on every DFS event.
1238 /// This interface of the DFS algorithm should be used in special cases
1239 /// when extra actions have to be performed in connection with certain
1240 /// events of the DFS algorithm. Otherwise consider to use Dfs or dfs()
1243 /// \tparam _Digraph The type of the digraph the algorithm runs on.
1244 /// The default value is
1245 /// \ref ListDigraph. The value of _Digraph is not used directly by
1246 /// \ref DfsVisit, it is only passed to \ref DfsVisitDefaultTraits.
1247 /// \tparam _Visitor The Visitor type that is used by the algorithm.
1248 /// \ref DfsVisitor "DfsVisitor<_Digraph>" is an empty visitor, which
1249 /// does not observe the DFS events. If you want to observe the DFS
1250 /// events, you should implement your own visitor class.
1251 /// \tparam _Traits Traits class to set various data types used by the
1252 /// algorithm. The default traits class is
1253 /// \ref DfsVisitDefaultTraits "DfsVisitDefaultTraits<_Digraph>".
1254 /// See \ref DfsVisitDefaultTraits for the documentation of
1255 /// a DFS visit traits class.
1257 template <typename _Digraph, typename _Visitor, typename _Traits>
1259 template <typename _Digraph = ListDigraph,
1260 typename _Visitor = DfsVisitor<_Digraph>,
1261 typename _Traits = DfsVisitDefaultTraits<_Digraph> >
1266 ///The traits class.
1267 typedef _Traits Traits;
1269 ///The type of the digraph the algorithm runs on.
1270 typedef typename Traits::Digraph Digraph;
1272 ///The visitor type used by the algorithm.
1273 typedef _Visitor Visitor;
1275 ///The type of the map that indicates which nodes are reached.
1276 typedef typename Traits::ReachedMap ReachedMap;
1280 typedef typename Digraph::Node Node;
1281 typedef typename Digraph::NodeIt NodeIt;
1282 typedef typename Digraph::Arc Arc;
1283 typedef typename Digraph::OutArcIt OutArcIt;
1285 //Pointer to the underlying digraph.
1286 const Digraph *_digraph;
1287 //Pointer to the visitor object.
1289 //Pointer to the map of reached status of the nodes.
1290 ReachedMap *_reached;
1291 //Indicates if _reached is locally allocated (true) or not.
1294 std::vector<typename Digraph::Arc> _stack;
1297 //Creates the maps if necessary.
1298 void create_maps() {
1300 local_reached = true;
1301 _reached = Traits::createReachedMap(*_digraph);
1311 typedef DfsVisit Create;
1313 /// \name Named template parameters
1317 struct SetReachedMapTraits : public Traits {
1318 typedef T ReachedMap;
1319 static ReachedMap *createReachedMap(const Digraph &digraph) {
1320 LEMON_ASSERT(false, "ReachedMap is not initialized");
1321 return 0; // ignore warnings
1324 /// \brief \ref named-templ-param "Named parameter" for setting
1325 /// ReachedMap type.
1327 /// \ref named-templ-param "Named parameter" for setting ReachedMap type.
1329 struct SetReachedMap : public DfsVisit< Digraph, Visitor,
1330 SetReachedMapTraits<T> > {
1331 typedef DfsVisit< Digraph, Visitor, SetReachedMapTraits<T> > Create;
1337 /// \brief Constructor.
1341 /// \param digraph The digraph the algorithm runs on.
1342 /// \param visitor The visitor object of the algorithm.
1343 DfsVisit(const Digraph& digraph, Visitor& visitor)
1344 : _digraph(&digraph), _visitor(&visitor),
1345 _reached(0), local_reached(false) {}
1347 /// \brief Destructor.
1349 if(local_reached) delete _reached;
1352 /// \brief Sets the map that indicates which nodes are reached.
1354 /// Sets the map that indicates which nodes are reached.
1355 /// If you don't use this function before calling \ref run(),
1356 /// it will allocate one. The destructor deallocates this
1357 /// automatically allocated map, of course.
1358 /// \return <tt> (*this) </tt>
1359 DfsVisit &reachedMap(ReachedMap &m) {
1362 local_reached=false;
1370 /// \name Execution control
1371 /// The simplest way to execute the algorithm is to use
1372 /// one of the member functions called \ref lemon::DfsVisit::run()
1375 /// If you need more control on the execution, first you must call
1376 /// \ref lemon::DfsVisit::init() "init()", then you can add several
1377 /// source nodes with \ref lemon::DfsVisit::addSource() "addSource()".
1378 /// Finally \ref lemon::DfsVisit::start() "start()" will perform the
1379 /// actual path computation.
1383 /// \brief Initializes the internal data structures.
1385 /// Initializes the internal data structures.
1388 _stack.resize(countNodes(*_digraph));
1390 for (NodeIt u(*_digraph) ; u != INVALID ; ++u) {
1391 _reached->set(u, false);
1395 ///Adds a new source node.
1397 ///Adds a new source node to the set of nodes to be processed.
1399 ///\pre The stack must be empty. (Otherwise the algorithm gives
1402 ///\warning Distances will be wrong (or at least strange) in case of
1403 ///multiple sources.
1404 void addSource(Node s)
1406 LEMON_DEBUG(emptyQueue(), "The stack is not empty.");
1407 if(!(*_reached)[s]) {
1408 _reached->set(s,true);
1412 _digraph->firstOut(e, s);
1414 _stack[++_stack_head] = e;
1421 /// \brief Processes the next arc.
1423 /// Processes the next arc.
1425 /// \return The processed arc.
1427 /// \pre The stack must not be empty.
1428 Arc processNextArc() {
1429 Arc e = _stack[_stack_head];
1430 Node m = _digraph->target(e);
1431 if(!(*_reached)[m]) {
1432 _visitor->discover(e);
1434 _reached->set(m, true);
1435 _digraph->firstOut(_stack[++_stack_head], m);
1437 _visitor->examine(e);
1438 m = _digraph->source(e);
1439 _digraph->nextOut(_stack[_stack_head]);
1441 while (_stack_head>=0 && _stack[_stack_head] == INVALID) {
1444 if (_stack_head >= 0) {
1445 _visitor->backtrack(_stack[_stack_head]);
1446 m = _digraph->source(_stack[_stack_head]);
1447 _digraph->nextOut(_stack[_stack_head]);
1455 /// \brief Next arc to be processed.
1457 /// Next arc to be processed.
1459 /// \return The next arc to be processed or INVALID if the stack is
1461 Arc nextArc() const {
1462 return _stack_head >= 0 ? _stack[_stack_head] : INVALID;
1465 /// \brief Returns \c false if there are nodes
1466 /// to be processed.
1468 /// Returns \c false if there are nodes
1469 /// to be processed in the queue (stack).
1470 bool emptyQueue() const { return _stack_head < 0; }
1472 /// \brief Returns the number of the nodes to be processed.
1474 /// Returns the number of the nodes to be processed in the queue (stack).
1475 int queueSize() const { return _stack_head + 1; }
1477 /// \brief Executes the algorithm.
1479 /// Executes the algorithm.
1481 /// This method runs the %DFS algorithm from the root node
1482 /// in order to compute the %DFS path to each node.
1484 /// The algorithm computes
1485 /// - the %DFS tree,
1486 /// - the distance of each node from the root in the %DFS tree.
1488 /// \pre init() must be called and a root node should be
1489 /// added with addSource() before using this function.
1491 /// \note <tt>d.start()</tt> is just a shortcut of the following code.
1493 /// while ( !d.emptyQueue() ) {
1494 /// d.processNextArc();
1498 while ( !emptyQueue() ) processNextArc();
1501 /// \brief Executes the algorithm until the given target node is reached.
1503 /// Executes the algorithm until the given target node is reached.
1505 /// This method runs the %DFS algorithm from the root node
1506 /// in order to compute the DFS path to \c t.
1508 /// The algorithm computes
1509 /// - the %DFS path to \c t,
1510 /// - the distance of \c t from the root in the %DFS tree.
1512 /// \pre init() must be called and a root node should be added
1513 /// with addSource() before using this function.
1514 void start(Node t) {
1515 while ( !emptyQueue() && _digraph->target(_stack[_stack_head]) != t )
1519 /// \brief Executes the algorithm until a condition is met.
1521 /// Executes the algorithm until a condition is met.
1523 /// This method runs the %DFS algorithm from the root node
1524 /// until an arc \c a with <tt>am[a]</tt> true is found.
1526 /// \param am A \c bool (or convertible) arc map. The algorithm
1527 /// will stop when it reaches an arc \c a with <tt>am[a]</tt> true.
1529 /// \return The reached arc \c a with <tt>am[a]</tt> true or
1530 /// \c INVALID if no such arc was found.
1532 /// \pre init() must be called and a root node should be added
1533 /// with addSource() before using this function.
1535 /// \warning Contrary to \ref Bfs and \ref Dijkstra, \c am is an arc map,
1537 template <typename AM>
1538 Arc start(const AM &am) {
1539 while ( !emptyQueue() && !am[_stack[_stack_head]] )
1541 return emptyQueue() ? INVALID : _stack[_stack_head];
1544 /// \brief Runs the algorithm from the given source node.
1546 /// This method runs the %DFS algorithm from node \c s.
1547 /// in order to compute the DFS path to each node.
1549 /// The algorithm computes
1550 /// - the %DFS tree,
1551 /// - the distance of each node from the root in the %DFS tree.
1553 /// \note <tt>d.run(s)</tt> is just a shortcut of the following code.
1565 /// \brief Finds the %DFS path between \c s and \c t.
1567 /// This method runs the %DFS algorithm from node \c s
1568 /// in order to compute the DFS path to node \c t
1569 /// (it stops searching when \c t is processed).
1571 /// \return \c true if \c t is reachable form \c s.
1573 /// \note Apart from the return value, <tt>d.run(s,t)</tt> is
1574 /// just a shortcut of the following code.
1580 bool run(Node s,Node t) {
1587 /// \brief Runs the algorithm to visit all nodes in the digraph.
1589 /// This method runs the %DFS algorithm in order to
1590 /// compute the %DFS path to each node.
1592 /// The algorithm computes
1593 /// - the %DFS tree,
1594 /// - the distance of each node from the root in the %DFS tree.
1596 /// \note <tt>d.run()</tt> is just a shortcut of the following code.
1599 /// for (NodeIt n(digraph); n != INVALID; ++n) {
1600 /// if (!d.reached(n)) {
1608 for (NodeIt it(*_digraph); it != INVALID; ++it) {
1618 /// \name Query Functions
1619 /// The result of the %DFS algorithm can be obtained using these
1621 /// Either \ref lemon::DfsVisit::run() "run()" or
1622 /// \ref lemon::DfsVisit::start() "start()" must be called before
1626 /// \brief Checks if a node is reachable from the root(s).
1628 /// Returns \c true if \c v is reachable from the root(s).
1629 /// \pre Either \ref run() or \ref start()
1630 /// must be called before using this function.
1631 bool reached(Node v) { return (*_reached)[v]; }
1637 } //END OF NAMESPACE LEMON