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>
36 /// \brief Default operation traits for the Dijkstra algorithm class.
38 /// This operation traits class defines all computational operations and
39 /// constants which are used in the Dijkstra algorithm.
40 template <typename Value>
41 struct DijkstraDefaultOperationTraits {
42 /// \brief Gives back the zero value of the type.
44 return static_cast<Value>(0);
46 /// \brief Gives back the sum of the given two elements.
47 static Value plus(const Value& left, const Value& right) {
50 /// \brief Gives back true only if the first value is less than the second.
51 static bool less(const Value& left, const Value& right) {
56 /// \brief Widest path operation traits for the Dijkstra algorithm class.
58 /// This operation traits class defines all computational operations and
59 /// constants which are used in the Dijkstra algorithm for widest path
62 /// \see DijkstraDefaultOperationTraits
63 template <typename Value>
64 struct DijkstraWidestPathOperationTraits {
65 /// \brief Gives back the maximum value of the type.
67 return std::numeric_limits<Value>::max();
69 /// \brief Gives back the minimum of the given two elements.
70 static Value plus(const Value& left, const Value& right) {
71 return std::min(left, right);
73 /// \brief Gives back true only if the first value is less than the second.
74 static bool less(const Value& left, const Value& right) {
79 ///Default traits class of Dijkstra class.
81 ///Default traits class of Dijkstra class.
82 ///\tparam GR The type of the digraph.
83 ///\tparam LM The type of the length map.
84 template<class GR, class LM>
85 struct DijkstraDefaultTraits
87 ///The type of the digraph the algorithm runs on.
90 ///The type of the map that stores the arc lengths.
92 ///The type of the map that stores the arc lengths.
93 ///It must meet the \ref concepts::ReadMap "ReadMap" concept.
95 ///The type of the length of the arcs.
96 typedef typename LM::Value Value;
98 /// Operation traits for Dijkstra algorithm.
100 /// This class defines the operations that are used in the algorithm.
101 /// \see DijkstraDefaultOperationTraits
102 typedef DijkstraDefaultOperationTraits<Value> OperationTraits;
104 /// The cross reference type used by the heap.
106 /// The cross reference type used by the heap.
107 /// Usually it is \c Digraph::NodeMap<int>.
108 typedef typename Digraph::template NodeMap<int> HeapCrossRef;
109 ///Instantiates a \ref HeapCrossRef.
111 ///This function instantiates a \ref HeapCrossRef.
112 /// \param g is the digraph, to which we would like to define the
113 /// \ref HeapCrossRef.
114 static HeapCrossRef *createHeapCrossRef(const Digraph &g)
116 return new HeapCrossRef(g);
119 ///The heap type used by the Dijkstra algorithm.
121 ///The heap type used by the Dijkstra algorithm.
125 typedef BinHeap<typename LM::Value, HeapCrossRef, std::less<Value> > Heap;
126 ///Instantiates a \ref Heap.
128 ///This function instantiates a \ref Heap.
129 static Heap *createHeap(HeapCrossRef& r)
134 ///\brief The type of the map that stores the predecessor
135 ///arcs of the shortest paths.
137 ///The type of the map that stores the predecessor
138 ///arcs of the shortest paths.
139 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
140 typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
141 ///Instantiates a \ref PredMap.
143 ///This function instantiates a \ref PredMap.
144 ///\param g is the digraph, to which we would like to define the
146 static PredMap *createPredMap(const Digraph &g)
148 return new PredMap(g);
151 ///The type of the map that indicates which nodes are processed.
153 ///The type of the map that indicates which nodes are processed.
154 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
155 ///By default it is a NullMap.
156 typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
157 ///Instantiates a \ref ProcessedMap.
159 ///This function instantiates a \ref ProcessedMap.
160 ///\param g is the digraph, to which
161 ///we would like to define the \ref ProcessedMap
163 static ProcessedMap *createProcessedMap(const Digraph &g)
165 static ProcessedMap *createProcessedMap(const Digraph &)
168 return new ProcessedMap();
171 ///The type of the map that stores the distances of the nodes.
173 ///The type of the map that stores the distances of the nodes.
174 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
175 typedef typename Digraph::template NodeMap<typename LM::Value> DistMap;
176 ///Instantiates a \ref DistMap.
178 ///This function instantiates a \ref DistMap.
179 ///\param g is the digraph, to which we would like to define
181 static DistMap *createDistMap(const Digraph &g)
183 return new DistMap(g);
187 ///%Dijkstra algorithm class.
189 /// \ingroup shortest_path
190 ///This class provides an efficient implementation of the %Dijkstra algorithm.
192 ///The arc lengths are passed to the algorithm using a
193 ///\ref concepts::ReadMap "ReadMap",
194 ///so it is easy to change it to any kind of length.
195 ///The type of the length is determined by the
196 ///\ref concepts::ReadMap::Value "Value" of the length map.
197 ///It is also possible to change the underlying priority heap.
199 ///There is also a \ref dijkstra() "function type interface" for the
200 ///%Dijkstra algorithm, which is convenient in the simplier cases and
201 ///it can be used easier.
203 ///\tparam GR The type of the digraph the algorithm runs on.
204 ///The default value is \ref ListDigraph.
205 ///The value of GR is not used directly by \ref Dijkstra, it is only
206 ///passed to \ref DijkstraDefaultTraits.
207 ///\tparam LM A readable arc map that determines the lengths of the
208 ///arcs. It is read once for each arc, so the map may involve in
209 ///relatively time consuming process to compute the arc lengths if
210 ///it is necessary. The default map type is \ref
211 ///concepts::Digraph::ArcMap "Digraph::ArcMap<int>".
212 ///The value of LM is not used directly by \ref Dijkstra, it is only
213 ///passed to \ref DijkstraDefaultTraits.
214 ///\tparam TR Traits class to set various data types used by the algorithm.
215 ///The default traits class is \ref DijkstraDefaultTraits
216 ///"DijkstraDefaultTraits<GR,LM>". See \ref DijkstraDefaultTraits
217 ///for the documentation of a Dijkstra traits class.
219 template <typename GR, typename LM, typename TR>
221 template <typename GR=ListDigraph,
222 typename LM=typename GR::template ArcMap<int>,
223 typename TR=DijkstraDefaultTraits<GR,LM> >
227 ///\ref Exception for uninitialized parameters.
229 ///This error represents problems in the initialization of the
230 ///parameters of the algorithm.
231 class UninitializedParameter : public lemon::UninitializedParameter {
233 virtual const char* what() const throw() {
234 return "lemon::Dijkstra::UninitializedParameter";
238 ///The type of the digraph the algorithm runs on.
239 typedef typename TR::Digraph Digraph;
241 ///The type of the length of the arcs.
242 typedef typename TR::LengthMap::Value Value;
243 ///The type of the map that stores the arc lengths.
244 typedef typename TR::LengthMap LengthMap;
245 ///\brief The type of the map that stores the predecessor arcs of the
247 typedef typename TR::PredMap PredMap;
248 ///The type of the map that stores the distances of the nodes.
249 typedef typename TR::DistMap DistMap;
250 ///The type of the map that indicates which nodes are processed.
251 typedef typename TR::ProcessedMap ProcessedMap;
252 ///The type of the paths.
253 typedef PredMapPath<Digraph, PredMap> Path;
254 ///The cross reference type used for the current heap.
255 typedef typename TR::HeapCrossRef HeapCrossRef;
256 ///The heap type used by the algorithm.
257 typedef typename TR::Heap Heap;
258 ///The operation traits class.
259 typedef typename TR::OperationTraits OperationTraits;
266 typedef typename Digraph::Node Node;
267 typedef typename Digraph::NodeIt NodeIt;
268 typedef typename Digraph::Arc Arc;
269 typedef typename Digraph::OutArcIt OutArcIt;
271 //Pointer to the underlying digraph.
273 //Pointer to the length map.
274 const LengthMap *length;
275 //Pointer to the map of predecessors arcs.
277 //Indicates if _pred is locally allocated (true) or not.
279 //Pointer to the map of distances.
281 //Indicates if _dist is locally allocated (true) or not.
283 //Pointer to the map of processed status of the nodes.
284 ProcessedMap *_processed;
285 //Indicates if _processed is locally allocated (true) or not.
286 bool local_processed;
287 //Pointer to the heap cross references.
288 HeapCrossRef *_heap_cross_ref;
289 //Indicates if _heap_cross_ref is locally allocated (true) or not.
290 bool local_heap_cross_ref;
291 //Pointer to the heap.
293 //Indicates if _heap is locally allocated (true) or not.
296 //Creates the maps if necessary.
301 _pred = Traits::createPredMap(*G);
305 _dist = Traits::createDistMap(*G);
308 local_processed = true;
309 _processed = Traits::createProcessedMap(*G);
311 if (!_heap_cross_ref) {
312 local_heap_cross_ref = true;
313 _heap_cross_ref = Traits::createHeapCrossRef(*G);
317 _heap = Traits::createHeap(*_heap_cross_ref);
323 typedef Dijkstra Create;
325 ///\name Named template parameters
330 struct SetPredMapTraits : public Traits {
332 static PredMap *createPredMap(const Digraph &)
334 throw UninitializedParameter();
337 ///\brief \ref named-templ-param "Named parameter" for setting
338 ///\ref PredMap type.
340 ///\ref named-templ-param "Named parameter" for setting
341 ///\ref PredMap type.
344 : public Dijkstra< Digraph, LengthMap, SetPredMapTraits<T> > {
345 typedef Dijkstra< Digraph, LengthMap, SetPredMapTraits<T> > Create;
349 struct SetDistMapTraits : public Traits {
351 static DistMap *createDistMap(const Digraph &)
353 throw UninitializedParameter();
356 ///\brief \ref named-templ-param "Named parameter" for setting
357 ///\ref DistMap type.
359 ///\ref named-templ-param "Named parameter" for setting
360 ///\ref DistMap type.
363 : public Dijkstra< Digraph, LengthMap, SetDistMapTraits<T> > {
364 typedef Dijkstra< Digraph, LengthMap, SetDistMapTraits<T> > Create;
368 struct SetProcessedMapTraits : public Traits {
369 typedef T ProcessedMap;
370 static ProcessedMap *createProcessedMap(const Digraph &)
372 throw UninitializedParameter();
375 ///\brief \ref named-templ-param "Named parameter" for setting
376 ///\ref ProcessedMap type.
378 ///\ref named-templ-param "Named parameter" for setting
379 ///\ref ProcessedMap type.
381 struct SetProcessedMap
382 : public Dijkstra< Digraph, LengthMap, SetProcessedMapTraits<T> > {
383 typedef Dijkstra< Digraph, LengthMap, SetProcessedMapTraits<T> > Create;
386 struct SetStandardProcessedMapTraits : public Traits {
387 typedef typename Digraph::template NodeMap<bool> ProcessedMap;
388 static ProcessedMap *createProcessedMap(const Digraph &g)
390 return new ProcessedMap(g);
393 ///\brief \ref named-templ-param "Named parameter" for setting
394 ///\ref ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
396 ///\ref named-templ-param "Named parameter" for setting
397 ///\ref ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
398 ///If you don't set it explicitly, it will be automatically allocated.
399 struct SetStandardProcessedMap
400 : public Dijkstra< Digraph, LengthMap, SetStandardProcessedMapTraits > {
401 typedef Dijkstra< Digraph, LengthMap, SetStandardProcessedMapTraits >
405 template <class H, class CR>
406 struct SetHeapTraits : public Traits {
407 typedef CR HeapCrossRef;
409 static HeapCrossRef *createHeapCrossRef(const Digraph &) {
410 throw UninitializedParameter();
412 static Heap *createHeap(HeapCrossRef &)
414 throw UninitializedParameter();
417 ///\brief \ref named-templ-param "Named parameter" for setting
418 ///heap and cross reference type
420 ///\ref named-templ-param "Named parameter" for setting heap and cross
422 template <class H, class CR = typename Digraph::template NodeMap<int> >
424 : public Dijkstra< Digraph, LengthMap, SetHeapTraits<H, CR> > {
425 typedef Dijkstra< Digraph, LengthMap, SetHeapTraits<H, CR> > Create;
428 template <class H, class CR>
429 struct SetStandardHeapTraits : public Traits {
430 typedef CR HeapCrossRef;
432 static HeapCrossRef *createHeapCrossRef(const Digraph &G) {
433 return new HeapCrossRef(G);
435 static Heap *createHeap(HeapCrossRef &R)
440 ///\brief \ref named-templ-param "Named parameter" for setting
441 ///heap and cross reference type with automatic allocation
443 ///\ref named-templ-param "Named parameter" for setting heap and cross
444 ///reference type. It can allocate the heap and the cross reference
445 ///object if the cross reference's constructor waits for the digraph as
446 ///parameter and the heap's constructor waits for the cross reference.
447 template <class H, class CR = typename Digraph::template NodeMap<int> >
448 struct SetStandardHeap
449 : public Dijkstra< Digraph, LengthMap, SetStandardHeapTraits<H, CR> > {
450 typedef Dijkstra< Digraph, LengthMap, SetStandardHeapTraits<H, CR> >
455 struct SetOperationTraitsTraits : public Traits {
456 typedef T OperationTraits;
459 /// \brief \ref named-templ-param "Named parameter" for setting
460 ///\ref OperationTraits type
462 ///\ref named-templ-param "Named parameter" for setting
463 ///\ref OperationTraits type.
465 struct SetOperationTraits
466 : public Dijkstra<Digraph, LengthMap, SetOperationTraitsTraits<T> > {
467 typedef Dijkstra<Digraph, LengthMap, SetOperationTraitsTraits<T> >
482 ///\param _g The digraph the algorithm runs on.
483 ///\param _length The length map used by the algorithm.
484 Dijkstra(const Digraph& _g, const LengthMap& _length) :
485 G(&_g), length(&_length),
486 _pred(NULL), local_pred(false),
487 _dist(NULL), local_dist(false),
488 _processed(NULL), local_processed(false),
489 _heap_cross_ref(NULL), local_heap_cross_ref(false),
490 _heap(NULL), local_heap(false)
496 if(local_pred) delete _pred;
497 if(local_dist) delete _dist;
498 if(local_processed) delete _processed;
499 if(local_heap_cross_ref) delete _heap_cross_ref;
500 if(local_heap) delete _heap;
503 ///Sets the length map.
505 ///Sets the length map.
506 ///\return <tt> (*this) </tt>
507 Dijkstra &lengthMap(const LengthMap &m)
513 ///Sets the map that stores the predecessor arcs.
515 ///Sets the map that stores the predecessor arcs.
516 ///If you don't use this function before calling \ref run(),
517 ///it will allocate one. The destructor deallocates this
518 ///automatically allocated map, of course.
519 ///\return <tt> (*this) </tt>
520 Dijkstra &predMap(PredMap &m)
530 ///Sets the map that indicates which nodes are processed.
532 ///Sets the map that indicates which nodes are processed.
533 ///If you don't use this function before calling \ref run(),
534 ///it will allocate one. The destructor deallocates this
535 ///automatically allocated map, of course.
536 ///\return <tt> (*this) </tt>
537 Dijkstra &processedMap(ProcessedMap &m)
539 if(local_processed) {
541 local_processed=false;
547 ///Sets the map that stores the distances of the nodes.
549 ///Sets the map that stores the distances of the nodes calculated by the
551 ///If you don't use this function before calling \ref run(),
552 ///it will allocate one. The destructor deallocates this
553 ///automatically allocated map, of course.
554 ///\return <tt> (*this) </tt>
555 Dijkstra &distMap(DistMap &m)
565 ///Sets the heap and the cross reference used by algorithm.
567 ///Sets the heap and the cross reference used by algorithm.
568 ///If you don't use this function before calling \ref run(),
569 ///it will allocate one. The destructor deallocates this
570 ///automatically allocated heap and cross reference, of course.
571 ///\return <tt> (*this) </tt>
572 Dijkstra &heap(Heap& hp, HeapCrossRef &cr)
574 if(local_heap_cross_ref) {
575 delete _heap_cross_ref;
576 local_heap_cross_ref=false;
578 _heap_cross_ref = &cr;
589 void finalizeNodeData(Node v,Value dst)
591 _processed->set(v,true);
597 ///\name Execution control
598 ///The simplest way to execute the algorithm is to use one of the
599 ///member functions called \ref lemon::Dijkstra::run() "run()".
601 ///If you need more control on the execution, first you must call
602 ///\ref lemon::Dijkstra::init() "init()", then you can add several
603 ///source nodes with \ref lemon::Dijkstra::addSource() "addSource()".
604 ///Finally \ref lemon::Dijkstra::start() "start()" will perform the
605 ///actual path computation.
609 ///Initializes the internal data structures.
611 ///Initializes the internal data structures.
617 for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
618 _pred->set(u,INVALID);
619 _processed->set(u,false);
620 _heap_cross_ref->set(u,Heap::PRE_HEAP);
624 ///Adds a new source node.
626 ///Adds a new source node to the priority heap.
627 ///The optional second parameter is the initial distance of the node.
629 ///The function checks if the node has already been added to the heap and
630 ///it is pushed to the heap only if either it was not in the heap
631 ///or the shortest path found till then is shorter than \c dst.
632 void addSource(Node s,Value dst=OperationTraits::zero())
634 if(_heap->state(s) != Heap::IN_HEAP) {
636 } else if(OperationTraits::less((*_heap)[s], dst)) {
638 _pred->set(s,INVALID);
642 ///Processes the next node in the priority heap
644 ///Processes the next node in the priority heap.
646 ///\return The processed node.
648 ///\warning The priority heap must not be empty.
649 Node processNextNode()
652 Value oldvalue=_heap->prio();
654 finalizeNodeData(v,oldvalue);
656 for(OutArcIt e(*G,v); e!=INVALID; ++e) {
658 switch(_heap->state(w)) {
660 _heap->push(w,OperationTraits::plus(oldvalue, (*length)[e]));
665 Value newvalue = OperationTraits::plus(oldvalue, (*length)[e]);
666 if ( OperationTraits::less(newvalue, (*_heap)[w]) ) {
667 _heap->decrease(w, newvalue);
672 case Heap::POST_HEAP:
679 ///The next node to be processed.
681 ///Returns the next node to be processed or \c INVALID if the
682 ///priority heap is empty.
683 Node nextNode() const
685 return !_heap->empty()?_heap->top():INVALID;
688 ///\brief Returns \c false if there are nodes
691 ///Returns \c false if there are nodes
692 ///to be processed in the priority heap.
693 bool emptyQueue() const { return _heap->empty(); }
695 ///Returns the number of the nodes to be processed in the priority heap
697 ///Returns the number of the nodes to be processed in the priority heap.
699 int queueSize() const { return _heap->size(); }
701 ///Executes the algorithm.
703 ///Executes the algorithm.
705 ///This method runs the %Dijkstra algorithm from the root node(s)
706 ///in order to compute the shortest path to each node.
708 ///The algorithm computes
709 ///- the shortest path tree (forest),
710 ///- the distance of each node from the root(s).
712 ///\pre init() must be called and at least one root node should be
713 ///added with addSource() before using this function.
715 ///\note <tt>d.start()</tt> is just a shortcut of the following code.
717 /// while ( !d.emptyQueue() ) {
718 /// d.processNextNode();
723 while ( !emptyQueue() ) processNextNode();
726 ///Executes the algorithm until the given target node is reached.
728 ///Executes the algorithm until the given target node is reached.
730 ///This method runs the %Dijkstra algorithm from the root node(s)
731 ///in order to compute the shortest path to \c dest.
733 ///The algorithm computes
734 ///- the shortest path to \c dest,
735 ///- the distance of \c dest from the root(s).
737 ///\pre init() must be called and at least one root node should be
738 ///added with addSource() before using this function.
739 void start(Node dest)
741 while ( !_heap->empty() && _heap->top()!=dest ) processNextNode();
742 if ( !_heap->empty() ) finalizeNodeData(_heap->top(),_heap->prio());
745 ///Executes the algorithm until a condition is met.
747 ///Executes the algorithm until a condition is met.
749 ///This method runs the %Dijkstra algorithm from the root node(s) in
750 ///order to compute the shortest path to a node \c v with
751 /// <tt>nm[v]</tt> true, if such a node can be found.
753 ///\param nm A \c bool (or convertible) node map. The algorithm
754 ///will stop when it reaches a node \c v with <tt>nm[v]</tt> true.
756 ///\return The reached node \c v with <tt>nm[v]</tt> true or
757 ///\c INVALID if no such node was found.
759 ///\pre init() must be called and at least one root node should be
760 ///added with addSource() before using this function.
761 template<class NodeBoolMap>
762 Node start(const NodeBoolMap &nm)
764 while ( !_heap->empty() && !nm[_heap->top()] ) processNextNode();
765 if ( _heap->empty() ) return INVALID;
766 finalizeNodeData(_heap->top(),_heap->prio());
770 ///Runs the algorithm from the given node.
772 ///This method runs the %Dijkstra algorithm from node \c s
773 ///in order to compute the shortest path to each node.
775 ///The algorithm computes
776 ///- the shortest path tree,
777 ///- the distance of each node from the root.
779 ///\note <tt>d.run(s)</tt> is just a shortcut of the following code.
791 ///Finds the shortest path between \c s and \c t.
793 ///This method runs the %Dijkstra algorithm from node \c s
794 ///in order to compute the shortest path to \c t.
796 ///\return The length of the shortest <tt>s</tt>--<tt>t</tt> path,
797 ///if \c t is reachable form \c s, \c 0 otherwise.
799 ///\note Apart from the return value, <tt>d.run(s,t)</tt> is just a
800 ///shortcut of the following code.
806 Value run(Node s,Node t) {
810 return (*_pred)[t]==INVALID?OperationTraits::zero():(*_dist)[t];
815 ///\name Query Functions
816 ///The result of the %Dijkstra algorithm can be obtained using these
818 ///Either \ref lemon::Dijkstra::run() "run()" or
819 ///\ref lemon::Dijkstra::start() "start()" must be called before
824 ///The shortest path to a node.
826 ///Returns the shortest path to a node.
828 ///\warning \c t should be reachable from the root(s).
830 ///\pre Either \ref run() or \ref start() must be called before
831 ///using this function.
832 Path path(Node t) const { return Path(*G, *_pred, t); }
834 ///The distance of a node from the root(s).
836 ///Returns the distance of a node from the root(s).
838 ///\warning If node \c v is not reachable from the root(s), then
839 ///the return value of this function is undefined.
841 ///\pre Either \ref run() or \ref start() must be called before
842 ///using this function.
843 Value dist(Node v) const { return (*_dist)[v]; }
845 ///Returns the 'previous arc' of the shortest path tree for a node.
847 ///This function returns the 'previous arc' of the shortest path
848 ///tree for the node \c v, i.e. it returns the last arc of a
849 ///shortest path from the root(s) to \c v. It is \c INVALID if \c v
850 ///is not reachable from the root(s) or if \c v is a root.
852 ///The shortest path tree used here is equal to the shortest path
853 ///tree used in \ref predNode().
855 ///\pre Either \ref run() or \ref start() must be called before
856 ///using this function.
857 Arc predArc(Node v) const { return (*_pred)[v]; }
859 ///Returns the 'previous node' of the shortest path tree for a node.
861 ///This function returns the 'previous node' of the shortest path
862 ///tree for the node \c v, i.e. it returns the last but one node
863 ///from a shortest path from the root(s) to \c v. It is \c INVALID
864 ///if \c v is not reachable from the root(s) or if \c v is a root.
866 ///The shortest path tree used here is equal to the shortest path
867 ///tree used in \ref predArc().
869 ///\pre Either \ref run() or \ref start() must be called before
870 ///using this function.
871 Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
872 G->source((*_pred)[v]); }
874 ///\brief Returns a const reference to the node map that stores the
875 ///distances of the nodes.
877 ///Returns a const reference to the node map that stores the distances
878 ///of the nodes calculated by the algorithm.
880 ///\pre Either \ref run() or \ref init()
881 ///must be called before using this function.
882 const DistMap &distMap() const { return *_dist;}
884 ///\brief Returns a const reference to the node map that stores the
887 ///Returns a const reference to the node map that stores the predecessor
888 ///arcs, which form the shortest path tree.
890 ///\pre Either \ref run() or \ref init()
891 ///must be called before using this function.
892 const PredMap &predMap() const { return *_pred;}
894 ///Checks if a node is reachable from the root(s).
896 ///Returns \c true if \c v is reachable from the root(s).
897 ///\pre Either \ref run() or \ref start()
898 ///must be called before using this function.
899 bool reached(Node v) const { return (*_heap_cross_ref)[v] !=
902 ///Checks if a node is processed.
904 ///Returns \c true if \c v is processed, i.e. the shortest
905 ///path to \c v has already found.
906 ///\pre Either \ref run() or \ref start()
907 ///must be called before using this function.
908 bool processed(Node v) const { return (*_heap_cross_ref)[v] ==
911 ///The current distance of a node from the root(s).
913 ///Returns the current distance of a node from the root(s).
914 ///It may be decreased in the following processes.
915 ///\pre \c v should be reached but not processed.
916 Value currentDist(Node v) const { return (*_heap)[v]; }
922 ///Default traits class of dijkstra() function.
924 ///Default traits class of dijkstra() function.
925 ///\tparam GR The type of the digraph.
926 ///\tparam LM The type of the length map.
927 template<class GR, class LM>
928 struct DijkstraWizardDefaultTraits
930 ///The type of the digraph the algorithm runs on.
932 ///The type of the map that stores the arc lengths.
934 ///The type of the map that stores the arc lengths.
935 ///It must meet the \ref concepts::ReadMap "ReadMap" concept.
936 typedef LM LengthMap;
937 ///The type of the length of the arcs.
938 typedef typename LM::Value Value;
940 /// Operation traits for Dijkstra algorithm.
942 /// This class defines the operations that are used in the algorithm.
943 /// \see DijkstraDefaultOperationTraits
944 typedef DijkstraDefaultOperationTraits<Value> OperationTraits;
946 /// The cross reference type used by the heap.
948 /// The cross reference type used by the heap.
949 /// Usually it is \c Digraph::NodeMap<int>.
950 typedef typename Digraph::template NodeMap<int> HeapCrossRef;
951 ///Instantiates a \ref HeapCrossRef.
953 ///This function instantiates a \ref HeapCrossRef.
954 /// \param g is the digraph, to which we would like to define the
956 static HeapCrossRef *createHeapCrossRef(const Digraph &g)
958 return new HeapCrossRef(g);
961 ///The heap type used by the Dijkstra algorithm.
963 ///The heap type used by the Dijkstra algorithm.
967 typedef BinHeap<Value, typename Digraph::template NodeMap<int>,
968 std::less<Value> > Heap;
970 ///Instantiates a \ref Heap.
972 ///This function instantiates a \ref Heap.
973 /// \param r is the HeapCrossRef which is used.
974 static Heap *createHeap(HeapCrossRef& r)
979 ///\brief The type of the map that stores the predecessor
980 ///arcs of the shortest paths.
982 ///The type of the map that stores the predecessor
983 ///arcs of the shortest paths.
984 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
985 typedef NullMap <typename Digraph::Node,typename Digraph::Arc> PredMap;
986 ///Instantiates a \ref PredMap.
988 ///This function instantiates a \ref PredMap.
989 ///\param g is the digraph, to which we would like to define the
992 static PredMap *createPredMap(const Digraph &g)
994 static PredMap *createPredMap(const Digraph &)
997 return new PredMap();
1000 ///The type of the map that indicates which nodes are processed.
1002 ///The type of the map that indicates which nodes are processed.
1003 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
1004 ///By default it is a NullMap.
1005 typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
1006 ///Instantiates a \ref ProcessedMap.
1008 ///This function instantiates a \ref ProcessedMap.
1009 ///\param g is the digraph, to which
1010 ///we would like to define the \ref ProcessedMap.
1012 static ProcessedMap *createProcessedMap(const Digraph &g)
1014 static ProcessedMap *createProcessedMap(const Digraph &)
1017 return new ProcessedMap();
1020 ///The type of the map that stores the distances of the nodes.
1022 ///The type of the map that stores the distances of the nodes.
1023 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
1024 typedef NullMap<typename Digraph::Node,Value> DistMap;
1025 ///Instantiates a \ref DistMap.
1027 ///This function instantiates a \ref DistMap.
1028 ///\param g is the digraph, to which we would like to define
1031 static DistMap *createDistMap(const Digraph &g)
1033 static DistMap *createDistMap(const Digraph &)
1036 return new DistMap();
1040 /// Default traits class used by \ref DijkstraWizard
1042 /// To make it easier to use Dijkstra algorithm
1043 /// we have created a wizard class.
1044 /// This \ref DijkstraWizard class needs default traits,
1045 /// as well as the \ref Dijkstra class.
1046 /// The \ref DijkstraWizardBase is a class to be the default traits of the
1047 /// \ref DijkstraWizard class.
1048 template<class GR,class LM>
1049 class DijkstraWizardBase : public DijkstraWizardDefaultTraits<GR,LM>
1051 typedef DijkstraWizardDefaultTraits<GR,LM> Base;
1053 //The type of the nodes in the digraph.
1054 typedef typename Base::Digraph::Node Node;
1056 //Pointer to the digraph the algorithm runs on.
1058 //Pointer to the length map
1060 //Pointer to the map of processed nodes.
1062 //Pointer to the map of predecessors arcs.
1064 //Pointer to the map of distances.
1066 //Pointer to the source node.
1072 /// This constructor does not require parameters, therefore it initiates
1073 /// all of the attributes to default values (0, INVALID).
1074 DijkstraWizardBase() : _g(0), _length(0), _processed(0), _pred(0),
1075 _dist(0), _source(INVALID) {}
1079 /// This constructor requires some parameters,
1080 /// listed in the parameters list.
1081 /// Others are initiated to 0.
1082 /// \param g The digraph the algorithm runs on.
1083 /// \param l The length map.
1084 /// \param s The source node.
1085 DijkstraWizardBase(const GR &g,const LM &l, Node s=INVALID) :
1086 _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
1087 _length(reinterpret_cast<void*>(const_cast<LM*>(&l))),
1088 _processed(0), _pred(0), _dist(0), _source(s) {}
1092 /// Auxiliary class for the function type interface of Dijkstra algorithm.
1094 /// This auxiliary class is created to implement the function type
1095 /// interface of \ref Dijkstra algorithm. It uses the functions and features
1096 /// of the plain \ref Dijkstra, but it is much simpler to use it.
1097 /// It should only be used through the \ref dijkstra() function, which makes
1098 /// it easier to use the algorithm.
1100 /// Simplicity means that the way to change the types defined
1101 /// in the traits class is based on functions that returns the new class
1102 /// and not on templatable built-in classes.
1103 /// When using the plain \ref Dijkstra
1104 /// the new class with the modified type comes from
1105 /// the original class by using the ::
1106 /// operator. In the case of \ref DijkstraWizard only
1107 /// a function have to be called, and it will
1108 /// return the needed class.
1110 /// It does not have own \ref run() method. When its \ref run() method
1111 /// is called, it initiates a plain \ref Dijkstra object, and calls the
1112 /// \ref Dijkstra::run() method of it.
1114 class DijkstraWizard : public TR
1118 ///The type of the digraph the algorithm runs on.
1119 typedef typename TR::Digraph Digraph;
1121 typedef typename Digraph::Node Node;
1122 typedef typename Digraph::NodeIt NodeIt;
1123 typedef typename Digraph::Arc Arc;
1124 typedef typename Digraph::OutArcIt OutArcIt;
1126 ///The type of the map that stores the arc lengths.
1127 typedef typename TR::LengthMap LengthMap;
1128 ///The type of the length of the arcs.
1129 typedef typename LengthMap::Value Value;
1130 ///\brief The type of the map that stores the predecessor
1131 ///arcs of the shortest paths.
1132 typedef typename TR::PredMap PredMap;
1133 ///The type of the map that stores the distances of the nodes.
1134 typedef typename TR::DistMap DistMap;
1135 ///The type of the map that indicates which nodes are processed.
1136 typedef typename TR::ProcessedMap ProcessedMap;
1137 ///The heap type used by the dijkstra algorithm.
1138 typedef typename TR::Heap Heap;
1143 DijkstraWizard() : TR() {}
1145 /// Constructor that requires parameters.
1147 /// Constructor that requires parameters.
1148 /// These parameters will be the default values for the traits class.
1149 DijkstraWizard(const Digraph &g,const LengthMap &l, Node s=INVALID) :
1153 DijkstraWizard(const TR &b) : TR(b) {}
1155 ~DijkstraWizard() {}
1157 ///Runs Dijkstra algorithm from a source node.
1159 ///Runs Dijkstra algorithm from a source node.
1160 ///The node can be given with the \ref source() function.
1163 if(Base::_source==INVALID) throw UninitializedParameter();
1164 Dijkstra<Digraph,LengthMap,TR>
1165 dij(*reinterpret_cast<const Digraph*>(Base::_g),
1166 *reinterpret_cast<const LengthMap*>(Base::_length));
1167 if(Base::_processed)
1168 dij.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1170 dij.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1172 dij.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1173 dij.run(Base::_source);
1176 ///Runs Dijkstra algorithm from the given node.
1178 ///Runs Dijkstra algorithm from the given node.
1179 ///\param s is the given source.
1186 /// Sets the source node, from which the Dijkstra algorithm runs.
1188 /// Sets the source node, from which the Dijkstra algorithm runs.
1189 /// \param s is the source node.
1190 DijkstraWizard<TR> &source(Node s)
1197 struct SetPredMapBase : public Base {
1199 static PredMap *createPredMap(const Digraph &) { return 0; };
1200 SetPredMapBase(const TR &b) : TR(b) {}
1202 ///\brief \ref named-templ-param "Named parameter"
1203 ///for setting \ref PredMap object.
1205 ///\ref named-templ-param "Named parameter"
1206 ///for setting \ref PredMap object.
1208 DijkstraWizard<SetPredMapBase<T> > predMap(const T &t)
1210 Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1211 return DijkstraWizard<SetPredMapBase<T> >(*this);
1215 struct SetProcessedMapBase : public Base {
1216 typedef T ProcessedMap;
1217 static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
1218 SetProcessedMapBase(const TR &b) : TR(b) {}
1220 ///\brief \ref named-templ-param "Named parameter"
1221 ///for setting \ref ProcessedMap object.
1223 /// \ref named-templ-param "Named parameter"
1224 ///for setting \ref ProcessedMap object.
1226 DijkstraWizard<SetProcessedMapBase<T> > processedMap(const T &t)
1228 Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1229 return DijkstraWizard<SetProcessedMapBase<T> >(*this);
1233 struct SetDistMapBase : public Base {
1235 static DistMap *createDistMap(const Digraph &) { return 0; };
1236 SetDistMapBase(const TR &b) : TR(b) {}
1238 ///\brief \ref named-templ-param "Named parameter"
1239 ///for setting \ref DistMap object.
1241 ///\ref named-templ-param "Named parameter"
1242 ///for setting \ref DistMap object.
1244 DijkstraWizard<SetDistMapBase<T> > distMap(const T &t)
1246 Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1247 return DijkstraWizard<SetDistMapBase<T> >(*this);
1252 ///Function type interface for Dijkstra algorithm.
1254 /// \ingroup shortest_path
1255 ///Function type interface for Dijkstra algorithm.
1257 ///This function also has several
1258 ///\ref named-templ-func-param "named parameters",
1259 ///they are declared as the members of class \ref DijkstraWizard.
1261 ///example shows how to use these parameters.
1263 /// dijkstra(g,length,source).predMap(preds).run();
1265 ///\warning Don't forget to put the \ref DijkstraWizard::run() "run()"
1266 ///to the end of the parameter list.
1267 ///\sa DijkstraWizard
1269 template<class GR, class LM>
1270 DijkstraWizard<DijkstraWizardBase<GR,LM> >
1271 dijkstra(const GR &g,const LM &l,typename GR::Node s=INVALID)
1273 return DijkstraWizard<DijkstraWizardBase<GR,LM> >(g,l,s);
1276 } //END OF NAMESPACE LEMON