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
19 #ifndef LEMON_DIJKSTRA_H
20 #define LEMON_DIJKSTRA_H
22 ///\ingroup shortest_path
24 ///\brief Dijkstra algorithm.
27 #include <lemon/list_graph.h>
28 #include <lemon/bin_heap.h>
29 #include <lemon/bits/path_dump.h>
30 #include <lemon/core.h>
31 #include <lemon/error.h>
32 #include <lemon/maps.h>
33 #include <lemon/path.h>
37 /// \brief Default operation traits for the Dijkstra algorithm class.
39 /// This operation traits class defines all computational operations and
40 /// constants which are used in the Dijkstra algorithm.
41 template <typename Value>
42 struct DijkstraDefaultOperationTraits {
43 /// \brief Gives back the zero value of the type.
45 return static_cast<Value>(0);
47 /// \brief Gives back the sum of the given two elements.
48 static Value plus(const Value& left, const Value& right) {
51 /// \brief Gives back true only if the first value is less than the second.
52 static bool less(const Value& left, const Value& right) {
57 ///Default traits class of Dijkstra class.
59 ///Default traits class of Dijkstra class.
60 ///\tparam GR The type of the digraph.
61 ///\tparam LM The type of the length map.
62 template<class GR, class LM>
63 struct DijkstraDefaultTraits
65 ///The type of the digraph the algorithm runs on.
68 ///The type of the map that stores the arc lengths.
70 ///The type of the map that stores the arc lengths.
71 ///It must meet the \ref concepts::ReadMap "ReadMap" concept.
73 ///The type of the length of the arcs.
74 typedef typename LM::Value Value;
76 /// Operation traits for Dijkstra algorithm.
78 /// This class defines the operations that are used in the algorithm.
79 /// \see DijkstraDefaultOperationTraits
80 typedef DijkstraDefaultOperationTraits<Value> OperationTraits;
82 /// The cross reference type used by the heap.
84 /// The cross reference type used by the heap.
85 /// Usually it is \c Digraph::NodeMap<int>.
86 typedef typename Digraph::template NodeMap<int> HeapCrossRef;
87 ///Instantiates a \ref HeapCrossRef.
89 ///This function instantiates a \ref HeapCrossRef.
90 /// \param g is the digraph, to which we would like to define the
91 /// \ref HeapCrossRef.
92 static HeapCrossRef *createHeapCrossRef(const Digraph &g)
94 return new HeapCrossRef(g);
97 ///The heap type used by the Dijkstra algorithm.
99 ///The heap type used by the Dijkstra algorithm.
103 typedef BinHeap<typename LM::Value, HeapCrossRef, std::less<Value> > Heap;
104 ///Instantiates a \ref Heap.
106 ///This function instantiates a \ref Heap.
107 static Heap *createHeap(HeapCrossRef& r)
112 ///\brief The type of the map that stores the predecessor
113 ///arcs of the shortest paths.
115 ///The type of the map that stores the predecessor
116 ///arcs of the shortest paths.
117 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
118 typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
119 ///Instantiates a PredMap.
121 ///This function instantiates a PredMap.
122 ///\param g is the digraph, to which we would like to define the
124 static PredMap *createPredMap(const Digraph &g)
126 return new PredMap(g);
129 ///The type of the map that indicates which nodes are processed.
131 ///The type of the map that indicates which nodes are processed.
132 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
133 ///By default it is a NullMap.
134 typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
135 ///Instantiates a ProcessedMap.
137 ///This function instantiates a ProcessedMap.
138 ///\param g is the digraph, to which
139 ///we would like to define the ProcessedMap
141 static ProcessedMap *createProcessedMap(const Digraph &g)
143 static ProcessedMap *createProcessedMap(const Digraph &)
146 return new ProcessedMap();
149 ///The type of the map that stores the distances of the nodes.
151 ///The type of the map that stores the distances of the nodes.
152 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
153 typedef typename Digraph::template NodeMap<typename LM::Value> DistMap;
154 ///Instantiates a DistMap.
156 ///This function instantiates a DistMap.
157 ///\param g is the digraph, to which we would like to define
159 static DistMap *createDistMap(const Digraph &g)
161 return new DistMap(g);
165 ///%Dijkstra algorithm class.
167 /// \ingroup shortest_path
168 ///This class provides an efficient implementation of the %Dijkstra algorithm.
170 ///The arc lengths are passed to the algorithm using a
171 ///\ref concepts::ReadMap "ReadMap",
172 ///so it is easy to change it to any kind of length.
173 ///The type of the length is determined by the
174 ///\ref concepts::ReadMap::Value "Value" of the length map.
175 ///It is also possible to change the underlying priority heap.
177 ///There is also a \ref dijkstra() "function-type interface" for the
178 ///%Dijkstra algorithm, which is convenient in the simplier cases and
179 ///it can be used easier.
181 ///\tparam GR The type of the digraph the algorithm runs on.
182 ///The default value is \ref ListDigraph.
183 ///The value of GR is not used directly by \ref Dijkstra, it is only
184 ///passed to \ref DijkstraDefaultTraits.
185 ///\tparam LM A readable arc map that determines the lengths of the
186 ///arcs. It is read once for each arc, so the map may involve in
187 ///relatively time consuming process to compute the arc lengths if
188 ///it is necessary. The default map type is \ref
189 ///concepts::Digraph::ArcMap "Digraph::ArcMap<int>".
190 ///The value of LM is not used directly by \ref Dijkstra, it is only
191 ///passed to \ref DijkstraDefaultTraits.
192 ///\tparam TR Traits class to set various data types used by the algorithm.
193 ///The default traits class is \ref DijkstraDefaultTraits
194 ///"DijkstraDefaultTraits<GR,LM>". See \ref DijkstraDefaultTraits
195 ///for the documentation of a Dijkstra traits class.
197 template <typename GR, typename LM, typename TR>
199 template <typename GR=ListDigraph,
200 typename LM=typename GR::template ArcMap<int>,
201 typename TR=DijkstraDefaultTraits<GR,LM> >
206 ///The type of the digraph the algorithm runs on.
207 typedef typename TR::Digraph Digraph;
209 ///The type of the length of the arcs.
210 typedef typename TR::LengthMap::Value Value;
211 ///The type of the map that stores the arc lengths.
212 typedef typename TR::LengthMap LengthMap;
213 ///\brief The type of the map that stores the predecessor arcs of the
215 typedef typename TR::PredMap PredMap;
216 ///The type of the map that stores the distances of the nodes.
217 typedef typename TR::DistMap DistMap;
218 ///The type of the map that indicates which nodes are processed.
219 typedef typename TR::ProcessedMap ProcessedMap;
220 ///The type of the paths.
221 typedef PredMapPath<Digraph, PredMap> Path;
222 ///The cross reference type used for the current heap.
223 typedef typename TR::HeapCrossRef HeapCrossRef;
224 ///The heap type used by the algorithm.
225 typedef typename TR::Heap Heap;
226 ///The operation traits class.
227 typedef typename TR::OperationTraits OperationTraits;
234 typedef typename Digraph::Node Node;
235 typedef typename Digraph::NodeIt NodeIt;
236 typedef typename Digraph::Arc Arc;
237 typedef typename Digraph::OutArcIt OutArcIt;
239 //Pointer to the underlying digraph.
241 //Pointer to the length map.
242 const LengthMap *length;
243 //Pointer to the map of predecessors arcs.
245 //Indicates if _pred is locally allocated (true) or not.
247 //Pointer to the map of distances.
249 //Indicates if _dist is locally allocated (true) or not.
251 //Pointer to the map of processed status of the nodes.
252 ProcessedMap *_processed;
253 //Indicates if _processed is locally allocated (true) or not.
254 bool local_processed;
255 //Pointer to the heap cross references.
256 HeapCrossRef *_heap_cross_ref;
257 //Indicates if _heap_cross_ref is locally allocated (true) or not.
258 bool local_heap_cross_ref;
259 //Pointer to the heap.
261 //Indicates if _heap is locally allocated (true) or not.
264 //Creates the maps if necessary.
269 _pred = Traits::createPredMap(*G);
273 _dist = Traits::createDistMap(*G);
276 local_processed = true;
277 _processed = Traits::createProcessedMap(*G);
279 if (!_heap_cross_ref) {
280 local_heap_cross_ref = true;
281 _heap_cross_ref = Traits::createHeapCrossRef(*G);
285 _heap = Traits::createHeap(*_heap_cross_ref);
291 typedef Dijkstra Create;
293 ///\name Named template parameters
298 struct SetPredMapTraits : public Traits {
300 static PredMap *createPredMap(const Digraph &)
302 LEMON_ASSERT(false, "PredMap is not initialized");
303 return 0; // ignore warnings
306 ///\brief \ref named-templ-param "Named parameter" for setting
309 ///\ref named-templ-param "Named parameter" for setting
313 : public Dijkstra< Digraph, LengthMap, SetPredMapTraits<T> > {
314 typedef Dijkstra< Digraph, LengthMap, SetPredMapTraits<T> > Create;
318 struct SetDistMapTraits : public Traits {
320 static DistMap *createDistMap(const Digraph &)
322 LEMON_ASSERT(false, "DistMap is not initialized");
323 return 0; // ignore warnings
326 ///\brief \ref named-templ-param "Named parameter" for setting
329 ///\ref named-templ-param "Named parameter" for setting
333 : public Dijkstra< Digraph, LengthMap, SetDistMapTraits<T> > {
334 typedef Dijkstra< Digraph, LengthMap, SetDistMapTraits<T> > Create;
338 struct SetProcessedMapTraits : public Traits {
339 typedef T ProcessedMap;
340 static ProcessedMap *createProcessedMap(const Digraph &)
342 LEMON_ASSERT(false, "ProcessedMap is not initialized");
343 return 0; // ignore warnings
346 ///\brief \ref named-templ-param "Named parameter" for setting
347 ///ProcessedMap type.
349 ///\ref named-templ-param "Named parameter" for setting
350 ///ProcessedMap type.
352 struct SetProcessedMap
353 : public Dijkstra< Digraph, LengthMap, SetProcessedMapTraits<T> > {
354 typedef Dijkstra< Digraph, LengthMap, SetProcessedMapTraits<T> > Create;
357 struct SetStandardProcessedMapTraits : public Traits {
358 typedef typename Digraph::template NodeMap<bool> ProcessedMap;
359 static ProcessedMap *createProcessedMap(const Digraph &g)
361 return new ProcessedMap(g);
364 ///\brief \ref named-templ-param "Named parameter" for setting
365 ///ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
367 ///\ref named-templ-param "Named parameter" for setting
368 ///ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
369 ///If you don't set it explicitly, it will be automatically allocated.
370 struct SetStandardProcessedMap
371 : public Dijkstra< Digraph, LengthMap, SetStandardProcessedMapTraits > {
372 typedef Dijkstra< Digraph, LengthMap, SetStandardProcessedMapTraits >
376 template <class H, class CR>
377 struct SetHeapTraits : public Traits {
378 typedef CR HeapCrossRef;
380 static HeapCrossRef *createHeapCrossRef(const Digraph &) {
381 LEMON_ASSERT(false, "HeapCrossRef is not initialized");
382 return 0; // ignore warnings
384 static Heap *createHeap(HeapCrossRef &)
386 LEMON_ASSERT(false, "Heap is not initialized");
387 return 0; // ignore warnings
390 ///\brief \ref named-templ-param "Named parameter" for setting
391 ///heap and cross reference type
393 ///\ref named-templ-param "Named parameter" for setting heap and cross
395 template <class H, class CR = typename Digraph::template NodeMap<int> >
397 : public Dijkstra< Digraph, LengthMap, SetHeapTraits<H, CR> > {
398 typedef Dijkstra< Digraph, LengthMap, SetHeapTraits<H, CR> > Create;
401 template <class H, class CR>
402 struct SetStandardHeapTraits : public Traits {
403 typedef CR HeapCrossRef;
405 static HeapCrossRef *createHeapCrossRef(const Digraph &G) {
406 return new HeapCrossRef(G);
408 static Heap *createHeap(HeapCrossRef &R)
413 ///\brief \ref named-templ-param "Named parameter" for setting
414 ///heap and cross reference type with automatic allocation
416 ///\ref named-templ-param "Named parameter" for setting heap and cross
417 ///reference type. It can allocate the heap and the cross reference
418 ///object if the cross reference's constructor waits for the digraph as
419 ///parameter and the heap's constructor waits for the cross reference.
420 template <class H, class CR = typename Digraph::template NodeMap<int> >
421 struct SetStandardHeap
422 : public Dijkstra< Digraph, LengthMap, SetStandardHeapTraits<H, CR> > {
423 typedef Dijkstra< Digraph, LengthMap, SetStandardHeapTraits<H, CR> >
428 struct SetOperationTraitsTraits : public Traits {
429 typedef T OperationTraits;
432 /// \brief \ref named-templ-param "Named parameter" for setting
433 ///\c OperationTraits type
435 ///\ref named-templ-param "Named parameter" for setting
436 ///\ref OperationTraits type.
438 struct SetOperationTraits
439 : public Dijkstra<Digraph, LengthMap, SetOperationTraitsTraits<T> > {
440 typedef Dijkstra<Digraph, LengthMap, SetOperationTraitsTraits<T> >
455 ///\param _g The digraph the algorithm runs on.
456 ///\param _length The length map used by the algorithm.
457 Dijkstra(const Digraph& _g, const LengthMap& _length) :
458 G(&_g), length(&_length),
459 _pred(NULL), local_pred(false),
460 _dist(NULL), local_dist(false),
461 _processed(NULL), local_processed(false),
462 _heap_cross_ref(NULL), local_heap_cross_ref(false),
463 _heap(NULL), local_heap(false)
469 if(local_pred) delete _pred;
470 if(local_dist) delete _dist;
471 if(local_processed) delete _processed;
472 if(local_heap_cross_ref) delete _heap_cross_ref;
473 if(local_heap) delete _heap;
476 ///Sets the length map.
478 ///Sets the length map.
479 ///\return <tt> (*this) </tt>
480 Dijkstra &lengthMap(const LengthMap &m)
486 ///Sets the map that stores the predecessor arcs.
488 ///Sets the map that stores the predecessor arcs.
489 ///If you don't use this function before calling \ref run(),
490 ///it will allocate one. The destructor deallocates this
491 ///automatically allocated map, of course.
492 ///\return <tt> (*this) </tt>
493 Dijkstra &predMap(PredMap &m)
503 ///Sets the map that indicates which nodes are processed.
505 ///Sets the map that indicates which nodes are processed.
506 ///If you don't use this function before calling \ref run(),
507 ///it will allocate one. The destructor deallocates this
508 ///automatically allocated map, of course.
509 ///\return <tt> (*this) </tt>
510 Dijkstra &processedMap(ProcessedMap &m)
512 if(local_processed) {
514 local_processed=false;
520 ///Sets the map that stores the distances of the nodes.
522 ///Sets the map that stores the distances of the nodes calculated by the
524 ///If you don't use this function before calling \ref run(),
525 ///it will allocate one. The destructor deallocates this
526 ///automatically allocated map, of course.
527 ///\return <tt> (*this) </tt>
528 Dijkstra &distMap(DistMap &m)
538 ///Sets the heap and the cross reference used by algorithm.
540 ///Sets the heap and the cross reference used by algorithm.
541 ///If you don't use this function before calling \ref run(),
542 ///it will allocate one. The destructor deallocates this
543 ///automatically allocated heap and cross reference, of course.
544 ///\return <tt> (*this) </tt>
545 Dijkstra &heap(Heap& hp, HeapCrossRef &cr)
547 if(local_heap_cross_ref) {
548 delete _heap_cross_ref;
549 local_heap_cross_ref=false;
551 _heap_cross_ref = &cr;
562 void finalizeNodeData(Node v,Value dst)
564 _processed->set(v,true);
570 ///\name Execution control
571 ///The simplest way to execute the algorithm is to use one of the
572 ///member functions called \ref lemon::Dijkstra::run() "run()".
574 ///If you need more control on the execution, first you must call
575 ///\ref lemon::Dijkstra::init() "init()", then you can add several
576 ///source nodes with \ref lemon::Dijkstra::addSource() "addSource()".
577 ///Finally \ref lemon::Dijkstra::start() "start()" will perform the
578 ///actual path computation.
582 ///Initializes the internal data structures.
584 ///Initializes the internal data structures.
590 for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
591 _pred->set(u,INVALID);
592 _processed->set(u,false);
593 _heap_cross_ref->set(u,Heap::PRE_HEAP);
597 ///Adds a new source node.
599 ///Adds a new source node to the priority heap.
600 ///The optional second parameter is the initial distance of the node.
602 ///The function checks if the node has already been added to the heap and
603 ///it is pushed to the heap only if either it was not in the heap
604 ///or the shortest path found till then is shorter than \c dst.
605 void addSource(Node s,Value dst=OperationTraits::zero())
607 if(_heap->state(s) != Heap::IN_HEAP) {
609 } else if(OperationTraits::less((*_heap)[s], dst)) {
611 _pred->set(s,INVALID);
615 ///Processes the next node in the priority heap
617 ///Processes the next node in the priority heap.
619 ///\return The processed node.
621 ///\warning The priority heap must not be empty.
622 Node processNextNode()
625 Value oldvalue=_heap->prio();
627 finalizeNodeData(v,oldvalue);
629 for(OutArcIt e(*G,v); e!=INVALID; ++e) {
631 switch(_heap->state(w)) {
633 _heap->push(w,OperationTraits::plus(oldvalue, (*length)[e]));
638 Value newvalue = OperationTraits::plus(oldvalue, (*length)[e]);
639 if ( OperationTraits::less(newvalue, (*_heap)[w]) ) {
640 _heap->decrease(w, newvalue);
645 case Heap::POST_HEAP:
652 ///The next node to be processed.
654 ///Returns the next node to be processed or \c INVALID if the
655 ///priority heap is empty.
656 Node nextNode() const
658 return !_heap->empty()?_heap->top():INVALID;
661 ///\brief Returns \c false if there are nodes
664 ///Returns \c false if there are nodes
665 ///to be processed in the priority heap.
666 bool emptyQueue() const { return _heap->empty(); }
668 ///Returns the number of the nodes to be processed in the priority heap
670 ///Returns the number of the nodes to be processed in the priority heap.
672 int queueSize() const { return _heap->size(); }
674 ///Executes the algorithm.
676 ///Executes the algorithm.
678 ///This method runs the %Dijkstra algorithm from the root node(s)
679 ///in order to compute the shortest path to each node.
681 ///The algorithm computes
682 ///- the shortest path tree (forest),
683 ///- the distance of each node from the root(s).
685 ///\pre init() must be called and at least one root node should be
686 ///added with addSource() before using this function.
688 ///\note <tt>d.start()</tt> is just a shortcut of the following code.
690 /// while ( !d.emptyQueue() ) {
691 /// d.processNextNode();
696 while ( !emptyQueue() ) processNextNode();
699 ///Executes the algorithm until the given target node is processed.
701 ///Executes the algorithm until the given target node is processed.
703 ///This method runs the %Dijkstra algorithm from the root node(s)
704 ///in order to compute the shortest path to \c t.
706 ///The algorithm computes
707 ///- the shortest path to \c t,
708 ///- the distance of \c t from the root(s).
710 ///\pre init() must be called and at least one root node should be
711 ///added with addSource() before using this function.
714 while ( !_heap->empty() && _heap->top()!=t ) processNextNode();
715 if ( !_heap->empty() ) {
716 finalizeNodeData(_heap->top(),_heap->prio());
721 ///Executes the algorithm until a condition is met.
723 ///Executes the algorithm until a condition is met.
725 ///This method runs the %Dijkstra algorithm from the root node(s) in
726 ///order to compute the shortest path to a node \c v with
727 /// <tt>nm[v]</tt> true, if such a node can be found.
729 ///\param nm A \c bool (or convertible) node map. The algorithm
730 ///will stop when it reaches a node \c v with <tt>nm[v]</tt> true.
732 ///\return The reached node \c v with <tt>nm[v]</tt> true or
733 ///\c INVALID if no such node was found.
735 ///\pre init() must be called and at least one root node should be
736 ///added with addSource() before using this function.
737 template<class NodeBoolMap>
738 Node start(const NodeBoolMap &nm)
740 while ( !_heap->empty() && !nm[_heap->top()] ) processNextNode();
741 if ( _heap->empty() ) return INVALID;
742 finalizeNodeData(_heap->top(),_heap->prio());
746 ///Runs the algorithm from the given source node.
748 ///This method runs the %Dijkstra algorithm from node \c s
749 ///in order to compute the shortest path to each node.
751 ///The algorithm computes
752 ///- the shortest path tree,
753 ///- the distance of each node from the root.
755 ///\note <tt>d.run(s)</tt> is just a shortcut of the following code.
767 ///Finds the shortest path between \c s and \c t.
769 ///This method runs the %Dijkstra algorithm from node \c s
770 ///in order to compute the shortest path to node \c t
771 ///(it stops searching when \c t is processed).
773 ///\return \c true if \c t is reachable form \c s.
775 ///\note Apart from the return value, <tt>d.run(s,t)</tt> is just a
776 ///shortcut of the following code.
782 bool run(Node s,Node t) {
786 return (*_heap_cross_ref)[t] == Heap::POST_HEAP;
791 ///\name Query Functions
792 ///The result of the %Dijkstra algorithm can be obtained using these
794 ///Either \ref lemon::Dijkstra::run() "run()" or
795 ///\ref lemon::Dijkstra::start() "start()" must be called before
800 ///The shortest path to a node.
802 ///Returns the shortest path to a node.
804 ///\warning \c t should be reachable from the root(s).
806 ///\pre Either \ref run() or \ref start() must be called before
807 ///using this function.
808 Path path(Node t) const { return Path(*G, *_pred, t); }
810 ///The distance of a node from the root(s).
812 ///Returns the distance of a node from the root(s).
814 ///\warning If node \c v is not reachable from the root(s), then
815 ///the return value of this function is undefined.
817 ///\pre Either \ref run() or \ref start() must be called before
818 ///using this function.
819 Value dist(Node v) const { return (*_dist)[v]; }
821 ///Returns the 'previous arc' of the shortest path tree for a node.
823 ///This function returns the 'previous arc' of the shortest path
824 ///tree for the node \c v, i.e. it returns the last arc of a
825 ///shortest path from the root(s) to \c v. It is \c INVALID if \c v
826 ///is not reachable from the root(s) or if \c v is a root.
828 ///The shortest path tree used here is equal to the shortest path
829 ///tree used in \ref predNode().
831 ///\pre Either \ref run() or \ref start() must be called before
832 ///using this function.
833 Arc predArc(Node v) const { return (*_pred)[v]; }
835 ///Returns the 'previous node' of the shortest path tree for a node.
837 ///This function returns the 'previous node' of the shortest path
838 ///tree for the node \c v, i.e. it returns the last but one node
839 ///from a shortest path from the root(s) to \c v. It is \c INVALID
840 ///if \c v is not reachable from the root(s) or if \c v is a root.
842 ///The shortest path tree used here is equal to the shortest path
843 ///tree used in \ref predArc().
845 ///\pre Either \ref run() or \ref start() must be called before
846 ///using this function.
847 Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
848 G->source((*_pred)[v]); }
850 ///\brief Returns a const reference to the node map that stores the
851 ///distances of the nodes.
853 ///Returns a const reference to the node map that stores the distances
854 ///of the nodes calculated by the algorithm.
856 ///\pre Either \ref run() or \ref init()
857 ///must be called before using this function.
858 const DistMap &distMap() const { return *_dist;}
860 ///\brief Returns a const reference to the node map that stores the
863 ///Returns a const reference to the node map that stores the predecessor
864 ///arcs, which form the shortest path tree.
866 ///\pre Either \ref run() or \ref init()
867 ///must be called before using this function.
868 const PredMap &predMap() const { return *_pred;}
870 ///Checks if a node is reachable from the root(s).
872 ///Returns \c true if \c v is reachable from the root(s).
873 ///\pre Either \ref run() or \ref start()
874 ///must be called before using this function.
875 bool reached(Node v) const { return (*_heap_cross_ref)[v] !=
878 ///Checks if a node is processed.
880 ///Returns \c true if \c v is processed, i.e. the shortest
881 ///path to \c v has already found.
882 ///\pre Either \ref run() or \ref init()
883 ///must be called before using this function.
884 bool processed(Node v) const { return (*_heap_cross_ref)[v] ==
887 ///The current distance of a node from the root(s).
889 ///Returns the current distance of a node from the root(s).
890 ///It may be decreased in the following processes.
891 ///\pre Either \ref run() or \ref init()
892 ///must be called before using this function and
893 ///node \c v must be reached but not necessarily processed.
894 Value currentDist(Node v) const {
895 return processed(v) ? (*_dist)[v] : (*_heap)[v];
902 ///Default traits class of dijkstra() function.
904 ///Default traits class of dijkstra() function.
905 ///\tparam GR The type of the digraph.
906 ///\tparam LM The type of the length map.
907 template<class GR, class LM>
908 struct DijkstraWizardDefaultTraits
910 ///The type of the digraph the algorithm runs on.
912 ///The type of the map that stores the arc lengths.
914 ///The type of the map that stores the arc lengths.
915 ///It must meet the \ref concepts::ReadMap "ReadMap" concept.
916 typedef LM LengthMap;
917 ///The type of the length of the arcs.
918 typedef typename LM::Value Value;
920 /// Operation traits for Dijkstra algorithm.
922 /// This class defines the operations that are used in the algorithm.
923 /// \see DijkstraDefaultOperationTraits
924 typedef DijkstraDefaultOperationTraits<Value> OperationTraits;
926 /// The cross reference type used by the heap.
928 /// The cross reference type used by the heap.
929 /// Usually it is \c Digraph::NodeMap<int>.
930 typedef typename Digraph::template NodeMap<int> HeapCrossRef;
931 ///Instantiates a \ref HeapCrossRef.
933 ///This function instantiates a \ref HeapCrossRef.
934 /// \param g is the digraph, to which we would like to define the
936 static HeapCrossRef *createHeapCrossRef(const Digraph &g)
938 return new HeapCrossRef(g);
941 ///The heap type used by the Dijkstra algorithm.
943 ///The heap type used by the Dijkstra algorithm.
947 typedef BinHeap<Value, typename Digraph::template NodeMap<int>,
948 std::less<Value> > Heap;
950 ///Instantiates a \ref Heap.
952 ///This function instantiates a \ref Heap.
953 /// \param r is the HeapCrossRef which is used.
954 static Heap *createHeap(HeapCrossRef& r)
959 ///\brief The type of the map that stores the predecessor
960 ///arcs of the shortest paths.
962 ///The type of the map that stores the predecessor
963 ///arcs of the shortest paths.
964 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
965 typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
966 ///Instantiates a PredMap.
968 ///This function instantiates a PredMap.
969 ///\param g is the digraph, to which we would like to define the
971 static PredMap *createPredMap(const Digraph &g)
973 return new PredMap(g);
976 ///The type of the map that indicates which nodes are processed.
978 ///The type of the map that indicates which nodes are processed.
979 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
980 ///By default it is a NullMap.
981 typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
982 ///Instantiates a ProcessedMap.
984 ///This function instantiates a ProcessedMap.
985 ///\param g is the digraph, to which
986 ///we would like to define the ProcessedMap.
988 static ProcessedMap *createProcessedMap(const Digraph &g)
990 static ProcessedMap *createProcessedMap(const Digraph &)
993 return new ProcessedMap();
996 ///The type of the map that stores the distances of the nodes.
998 ///The type of the map that stores the distances of the nodes.
999 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
1000 typedef typename Digraph::template NodeMap<typename LM::Value> DistMap;
1001 ///Instantiates a DistMap.
1003 ///This function instantiates a DistMap.
1004 ///\param g is the digraph, to which we would like to define
1006 static DistMap *createDistMap(const Digraph &g)
1008 return new DistMap(g);
1011 ///The type of the shortest paths.
1013 ///The type of the shortest paths.
1014 ///It must meet the \ref concepts::Path "Path" concept.
1015 typedef lemon::Path<Digraph> Path;
1018 /// Default traits class used by DijkstraWizard
1020 /// To make it easier to use Dijkstra algorithm
1021 /// we have created a wizard class.
1022 /// This \ref DijkstraWizard class needs default traits,
1023 /// as well as the \ref Dijkstra class.
1024 /// The \ref DijkstraWizardBase is a class to be the default traits of the
1025 /// \ref DijkstraWizard class.
1026 template<class GR,class LM>
1027 class DijkstraWizardBase : public DijkstraWizardDefaultTraits<GR,LM>
1029 typedef DijkstraWizardDefaultTraits<GR,LM> Base;
1031 //The type of the nodes in the digraph.
1032 typedef typename Base::Digraph::Node Node;
1034 //Pointer to the digraph the algorithm runs on.
1036 //Pointer to the length map.
1038 //Pointer to the map of processed nodes.
1040 //Pointer to the map of predecessors arcs.
1042 //Pointer to the map of distances.
1044 //Pointer to the shortest path to the target node.
1046 //Pointer to the distance of the target node.
1052 /// This constructor does not require parameters, therefore it initiates
1053 /// all of the attributes to \c 0.
1054 DijkstraWizardBase() : _g(0), _length(0), _processed(0), _pred(0),
1055 _dist(0), _path(0), _di(0) {}
1059 /// This constructor requires two parameters,
1060 /// others are initiated to \c 0.
1061 /// \param g The digraph the algorithm runs on.
1062 /// \param l The length map.
1063 DijkstraWizardBase(const GR &g,const LM &l) :
1064 _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
1065 _length(reinterpret_cast<void*>(const_cast<LM*>(&l))),
1066 _processed(0), _pred(0), _dist(0), _path(0), _di(0) {}
1070 /// Auxiliary class for the function-type interface of Dijkstra algorithm.
1072 /// This auxiliary class is created to implement the
1073 /// \ref dijkstra() "function-type interface" of \ref Dijkstra algorithm.
1074 /// It does not have own \ref run() method, it uses the functions
1075 /// and features of the plain \ref Dijkstra.
1077 /// This class should only be used through the \ref dijkstra() function,
1078 /// which makes it easier to use the algorithm.
1080 class DijkstraWizard : public TR
1084 ///The type of the digraph the algorithm runs on.
1085 typedef typename TR::Digraph Digraph;
1087 typedef typename Digraph::Node Node;
1088 typedef typename Digraph::NodeIt NodeIt;
1089 typedef typename Digraph::Arc Arc;
1090 typedef typename Digraph::OutArcIt OutArcIt;
1092 ///The type of the map that stores the arc lengths.
1093 typedef typename TR::LengthMap LengthMap;
1094 ///The type of the length of the arcs.
1095 typedef typename LengthMap::Value Value;
1096 ///\brief The type of the map that stores the predecessor
1097 ///arcs of the shortest paths.
1098 typedef typename TR::PredMap PredMap;
1099 ///The type of the map that stores the distances of the nodes.
1100 typedef typename TR::DistMap DistMap;
1101 ///The type of the map that indicates which nodes are processed.
1102 typedef typename TR::ProcessedMap ProcessedMap;
1103 ///The type of the shortest paths
1104 typedef typename TR::Path Path;
1105 ///The heap type used by the dijkstra algorithm.
1106 typedef typename TR::Heap Heap;
1111 DijkstraWizard() : TR() {}
1113 /// Constructor that requires parameters.
1115 /// Constructor that requires parameters.
1116 /// These parameters will be the default values for the traits class.
1117 /// \param g The digraph the algorithm runs on.
1118 /// \param l The length map.
1119 DijkstraWizard(const Digraph &g, const LengthMap &l) :
1123 DijkstraWizard(const TR &b) : TR(b) {}
1125 ~DijkstraWizard() {}
1127 ///Runs Dijkstra algorithm from the given source node.
1129 ///This method runs %Dijkstra algorithm from the given source node
1130 ///in order to compute the shortest path to each node.
1133 Dijkstra<Digraph,LengthMap,TR>
1134 dijk(*reinterpret_cast<const Digraph*>(Base::_g),
1135 *reinterpret_cast<const LengthMap*>(Base::_length));
1137 dijk.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1139 dijk.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1140 if (Base::_processed)
1141 dijk.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1145 ///Finds the shortest path between \c s and \c t.
1147 ///This method runs the %Dijkstra algorithm from node \c s
1148 ///in order to compute the shortest path to node \c t
1149 ///(it stops searching when \c t is processed).
1151 ///\return \c true if \c t is reachable form \c s.
1152 bool run(Node s, Node t)
1154 Dijkstra<Digraph,LengthMap,TR>
1155 dijk(*reinterpret_cast<const Digraph*>(Base::_g),
1156 *reinterpret_cast<const LengthMap*>(Base::_length));
1158 dijk.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1160 dijk.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1161 if (Base::_processed)
1162 dijk.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1165 *reinterpret_cast<Path*>(Base::_path) = dijk.path(t);
1167 *reinterpret_cast<Value*>(Base::_di) = dijk.dist(t);
1168 return dijk.reached(t);
1172 struct SetPredMapBase : public Base {
1174 static PredMap *createPredMap(const Digraph &) { return 0; };
1175 SetPredMapBase(const TR &b) : TR(b) {}
1177 ///\brief \ref named-func-param "Named parameter"
1178 ///for setting PredMap object.
1180 ///\ref named-func-param "Named parameter"
1181 ///for setting PredMap object.
1183 DijkstraWizard<SetPredMapBase<T> > predMap(const T &t)
1185 Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1186 return DijkstraWizard<SetPredMapBase<T> >(*this);
1190 struct SetDistMapBase : public Base {
1192 static DistMap *createDistMap(const Digraph &) { return 0; };
1193 SetDistMapBase(const TR &b) : TR(b) {}
1195 ///\brief \ref named-func-param "Named parameter"
1196 ///for setting DistMap object.
1198 ///\ref named-func-param "Named parameter"
1199 ///for setting DistMap object.
1201 DijkstraWizard<SetDistMapBase<T> > distMap(const T &t)
1203 Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1204 return DijkstraWizard<SetDistMapBase<T> >(*this);
1208 struct SetProcessedMapBase : public Base {
1209 typedef T ProcessedMap;
1210 static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
1211 SetProcessedMapBase(const TR &b) : TR(b) {}
1213 ///\brief \ref named-func-param "Named parameter"
1214 ///for setting ProcessedMap object.
1216 /// \ref named-func-param "Named parameter"
1217 ///for setting ProcessedMap object.
1219 DijkstraWizard<SetProcessedMapBase<T> > processedMap(const T &t)
1221 Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1222 return DijkstraWizard<SetProcessedMapBase<T> >(*this);
1226 struct SetPathBase : public Base {
1228 SetPathBase(const TR &b) : TR(b) {}
1230 ///\brief \ref named-func-param "Named parameter"
1231 ///for getting the shortest path to the target node.
1233 ///\ref named-func-param "Named parameter"
1234 ///for getting the shortest path to the target node.
1236 DijkstraWizard<SetPathBase<T> > path(const T &t)
1238 Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t));
1239 return DijkstraWizard<SetPathBase<T> >(*this);
1242 ///\brief \ref named-func-param "Named parameter"
1243 ///for getting the distance of the target node.
1245 ///\ref named-func-param "Named parameter"
1246 ///for getting the distance of the target node.
1247 DijkstraWizard dist(const Value &d)
1249 Base::_di=reinterpret_cast<void*>(const_cast<Value*>(&d));
1255 ///Function-type interface for Dijkstra algorithm.
1257 /// \ingroup shortest_path
1258 ///Function-type interface for Dijkstra algorithm.
1260 ///This function also has several \ref named-func-param "named parameters",
1261 ///they are declared as the members of class \ref DijkstraWizard.
1262 ///The following examples show how to use these parameters.
1264 /// // Compute shortest path from node s to each node
1265 /// dijkstra(g,length).predMap(preds).distMap(dists).run(s);
1267 /// // Compute shortest path from s to t
1268 /// bool reached = dijkstra(g,length).path(p).dist(d).run(s,t);
1270 ///\warning Don't forget to put the \ref DijkstraWizard::run() "run()"
1271 ///to the end of the parameter list.
1272 ///\sa DijkstraWizard
1274 template<class GR, class LM>
1275 DijkstraWizard<DijkstraWizardBase<GR,LM> >
1276 dijkstra(const GR &digraph, const LM &length)
1278 return DijkstraWizard<DijkstraWizardBase<GR,LM> >(digraph,length);
1281 } //END OF NAMESPACE LEMON