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 ///\todo The digraph alone may be insufficient for the initialization
147 static PredMap *createPredMap(const Digraph &g)
149 return new PredMap(g);
152 ///The type of the map that indicates which nodes are processed.
154 ///The type of the map that indicates which nodes are processed.
155 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
156 ///By default it is a NullMap.
157 ///\todo If it is set to a real map,
158 ///Dijkstra::processed() should read this.
159 typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
160 ///Instantiates a \ref ProcessedMap.
162 ///This function instantiates a \ref ProcessedMap.
163 ///\param g is the digraph, to which
164 ///we would like to define the \ref ProcessedMap
166 static ProcessedMap *createProcessedMap(const Digraph &g)
168 static ProcessedMap *createProcessedMap(const Digraph &)
171 return new ProcessedMap();
174 ///The type of the map that stores the distances of the nodes.
176 ///The type of the map that stores the distances of the nodes.
177 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
178 typedef typename Digraph::template NodeMap<typename LM::Value> DistMap;
179 ///Instantiates a \ref DistMap.
181 ///This function instantiates a \ref DistMap.
182 ///\param g is the digraph, to which we would like to define
184 static DistMap *createDistMap(const Digraph &g)
186 return new DistMap(g);
190 ///%Dijkstra algorithm class.
192 /// \ingroup shortest_path
193 ///This class provides an efficient implementation of the %Dijkstra algorithm.
195 ///The arc lengths are passed to the algorithm using a
196 ///\ref concepts::ReadMap "ReadMap",
197 ///so it is easy to change it to any kind of length.
198 ///The type of the length is determined by the
199 ///\ref concepts::ReadMap::Value "Value" of the length map.
200 ///It is also possible to change the underlying priority heap.
202 ///There is also a \ref dijkstra() "function type interface" for the
203 ///%Dijkstra algorithm, which is convenient in the simplier cases and
204 ///it can be used easier.
206 ///\tparam GR The type of the digraph the algorithm runs on.
207 ///The default value is \ref ListDigraph.
208 ///The value of GR is not used directly by \ref Dijkstra, it is only
209 ///passed to \ref DijkstraDefaultTraits.
210 ///\tparam LM A readable arc map that determines the lengths of the
211 ///arcs. It is read once for each arc, so the map may involve in
212 ///relatively time consuming process to compute the arc lengths if
213 ///it is necessary. The default map type is \ref
214 ///concepts::Digraph::ArcMap "Digraph::ArcMap<int>".
215 ///The value of LM is not used directly by \ref Dijkstra, it is only
216 ///passed to \ref DijkstraDefaultTraits.
217 ///\tparam TR Traits class to set various data types used by the algorithm.
218 ///The default traits class is \ref DijkstraDefaultTraits
219 ///"DijkstraDefaultTraits<GR,LM>". See \ref DijkstraDefaultTraits
220 ///for the documentation of a Dijkstra traits class.
222 template <typename GR, typename LM, typename TR>
224 template <typename GR=ListDigraph,
225 typename LM=typename GR::template ArcMap<int>,
226 typename TR=DijkstraDefaultTraits<GR,LM> >
230 ///\ref Exception for uninitialized parameters.
232 ///This error represents problems in the initialization of the
233 ///parameters of the algorithm.
234 class UninitializedParameter : public lemon::UninitializedParameter {
236 virtual const char* what() const throw() {
237 return "lemon::Dijkstra::UninitializedParameter";
241 ///The type of the digraph the algorithm runs on.
242 typedef typename TR::Digraph Digraph;
244 ///The type of the length of the arcs.
245 typedef typename TR::LengthMap::Value Value;
246 ///The type of the map that stores the arc lengths.
247 typedef typename TR::LengthMap LengthMap;
248 ///\brief The type of the map that stores the predecessor arcs of the
250 typedef typename TR::PredMap PredMap;
251 ///The type of the map that stores the distances of the nodes.
252 typedef typename TR::DistMap DistMap;
253 ///The type of the map that indicates which nodes are processed.
254 typedef typename TR::ProcessedMap ProcessedMap;
255 ///The type of the paths.
256 typedef PredMapPath<Digraph, PredMap> Path;
257 ///The cross reference type used for the current heap.
258 typedef typename TR::HeapCrossRef HeapCrossRef;
259 ///The heap type used by the algorithm.
260 typedef typename TR::Heap Heap;
261 ///The operation traits class.
262 typedef typename TR::OperationTraits OperationTraits;
269 typedef typename Digraph::Node Node;
270 typedef typename Digraph::NodeIt NodeIt;
271 typedef typename Digraph::Arc Arc;
272 typedef typename Digraph::OutArcIt OutArcIt;
274 //Pointer to the underlying digraph.
276 //Pointer to the length map.
277 const LengthMap *length;
278 //Pointer to the map of predecessors arcs.
280 //Indicates if _pred is locally allocated (true) or not.
282 //Pointer to the map of distances.
284 //Indicates if _dist is locally allocated (true) or not.
286 //Pointer to the map of processed status of the nodes.
287 ProcessedMap *_processed;
288 //Indicates if _processed is locally allocated (true) or not.
289 bool local_processed;
290 //Pointer to the heap cross references.
291 HeapCrossRef *_heap_cross_ref;
292 //Indicates if _heap_cross_ref is locally allocated (true) or not.
293 bool local_heap_cross_ref;
294 //Pointer to the heap.
296 //Indicates if _heap is locally allocated (true) or not.
299 ///Creates the maps if necessary.
300 ///\todo Better memory allocation (instead of new).
305 _pred = Traits::createPredMap(*G);
309 _dist = Traits::createDistMap(*G);
312 local_processed = true;
313 _processed = Traits::createProcessedMap(*G);
315 if (!_heap_cross_ref) {
316 local_heap_cross_ref = true;
317 _heap_cross_ref = Traits::createHeapCrossRef(*G);
321 _heap = Traits::createHeap(*_heap_cross_ref);
327 typedef Dijkstra Create;
329 ///\name Named template parameters
334 struct SetPredMapTraits : public Traits {
336 static PredMap *createPredMap(const Digraph &)
338 throw UninitializedParameter();
341 ///\brief \ref named-templ-param "Named parameter" for setting
342 ///\ref PredMap type.
344 ///\ref named-templ-param "Named parameter" for setting
345 ///\ref PredMap type.
348 : public Dijkstra< Digraph, LengthMap, SetPredMapTraits<T> > {
349 typedef Dijkstra< Digraph, LengthMap, SetPredMapTraits<T> > Create;
353 struct SetDistMapTraits : public Traits {
355 static DistMap *createDistMap(const Digraph &)
357 throw UninitializedParameter();
360 ///\brief \ref named-templ-param "Named parameter" for setting
361 ///\ref DistMap type.
363 ///\ref named-templ-param "Named parameter" for setting
364 ///\ref DistMap type.
367 : public Dijkstra< Digraph, LengthMap, SetDistMapTraits<T> > {
368 typedef Dijkstra< Digraph, LengthMap, SetDistMapTraits<T> > Create;
372 struct SetProcessedMapTraits : public Traits {
373 typedef T ProcessedMap;
374 static ProcessedMap *createProcessedMap(const Digraph &)
376 throw UninitializedParameter();
379 ///\brief \ref named-templ-param "Named parameter" for setting
380 ///\ref ProcessedMap type.
382 ///\ref named-templ-param "Named parameter" for setting
383 ///\ref ProcessedMap type.
385 struct SetProcessedMap
386 : public Dijkstra< Digraph, LengthMap, SetProcessedMapTraits<T> > {
387 typedef Dijkstra< Digraph, LengthMap, SetProcessedMapTraits<T> > Create;
390 struct SetStandardProcessedMapTraits : public Traits {
391 typedef typename Digraph::template NodeMap<bool> ProcessedMap;
392 static ProcessedMap *createProcessedMap(const Digraph &g)
394 return new ProcessedMap(g);
397 ///\brief \ref named-templ-param "Named parameter" for setting
398 ///\ref ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
400 ///\ref named-templ-param "Named parameter" for setting
401 ///\ref ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
402 ///If you don't set it explicitly, it will be automatically allocated.
403 struct SetStandardProcessedMap
404 : public Dijkstra< Digraph, LengthMap, SetStandardProcessedMapTraits > {
405 typedef Dijkstra< Digraph, LengthMap, SetStandardProcessedMapTraits >
409 template <class H, class CR>
410 struct SetHeapTraits : public Traits {
411 typedef CR HeapCrossRef;
413 static HeapCrossRef *createHeapCrossRef(const Digraph &) {
414 throw UninitializedParameter();
416 static Heap *createHeap(HeapCrossRef &)
418 throw UninitializedParameter();
421 ///\brief \ref named-templ-param "Named parameter" for setting
422 ///heap and cross reference type
424 ///\ref named-templ-param "Named parameter" for setting heap and cross
426 template <class H, class CR = typename Digraph::template NodeMap<int> >
428 : public Dijkstra< Digraph, LengthMap, SetHeapTraits<H, CR> > {
429 typedef Dijkstra< Digraph, LengthMap, SetHeapTraits<H, CR> > Create;
432 template <class H, class CR>
433 struct SetStandardHeapTraits : public Traits {
434 typedef CR HeapCrossRef;
436 static HeapCrossRef *createHeapCrossRef(const Digraph &G) {
437 return new HeapCrossRef(G);
439 static Heap *createHeap(HeapCrossRef &R)
444 ///\brief \ref named-templ-param "Named parameter" for setting
445 ///heap and cross reference type with automatic allocation
447 ///\ref named-templ-param "Named parameter" for setting heap and cross
448 ///reference type. It can allocate the heap and the cross reference
449 ///object if the cross reference's constructor waits for the digraph as
450 ///parameter and the heap's constructor waits for the cross reference.
451 template <class H, class CR = typename Digraph::template NodeMap<int> >
452 struct SetStandardHeap
453 : public Dijkstra< Digraph, LengthMap, SetStandardHeapTraits<H, CR> > {
454 typedef Dijkstra< Digraph, LengthMap, SetStandardHeapTraits<H, CR> >
459 struct SetOperationTraitsTraits : public Traits {
460 typedef T OperationTraits;
463 /// \brief \ref named-templ-param "Named parameter" for setting
464 ///\ref OperationTraits type
466 ///\ref named-templ-param "Named parameter" for setting
467 ///\ref OperationTraits type.
469 struct SetOperationTraits
470 : public Dijkstra<Digraph, LengthMap, SetOperationTraitsTraits<T> > {
471 typedef Dijkstra<Digraph, LengthMap, SetOperationTraitsTraits<T> >
486 ///\param _g The digraph the algorithm runs on.
487 ///\param _length The length map used by the algorithm.
488 Dijkstra(const Digraph& _g, const LengthMap& _length) :
489 G(&_g), length(&_length),
490 _pred(NULL), local_pred(false),
491 _dist(NULL), local_dist(false),
492 _processed(NULL), local_processed(false),
493 _heap_cross_ref(NULL), local_heap_cross_ref(false),
494 _heap(NULL), local_heap(false)
500 if(local_pred) delete _pred;
501 if(local_dist) delete _dist;
502 if(local_processed) delete _processed;
503 if(local_heap_cross_ref) delete _heap_cross_ref;
504 if(local_heap) delete _heap;
507 ///Sets the length map.
509 ///Sets the length map.
510 ///\return <tt> (*this) </tt>
511 Dijkstra &lengthMap(const LengthMap &m)
517 ///Sets the map that stores the predecessor arcs.
519 ///Sets the map that stores the predecessor arcs.
520 ///If you don't use this function before calling \ref run(),
521 ///it will allocate one. The destructor deallocates this
522 ///automatically allocated map, of course.
523 ///\return <tt> (*this) </tt>
524 Dijkstra &predMap(PredMap &m)
534 ///Sets the map that indicates which nodes are processed.
536 ///Sets the map that indicates which nodes are processed.
537 ///If you don't use this function before calling \ref run(),
538 ///it will allocate one. The destructor deallocates this
539 ///automatically allocated map, of course.
540 ///\return <tt> (*this) </tt>
541 Dijkstra &processedMap(ProcessedMap &m)
543 if(local_processed) {
545 local_processed=false;
551 ///Sets the map that stores the distances of the nodes.
553 ///Sets the map that stores the distances of the nodes calculated by the
555 ///If you don't use this function before calling \ref run(),
556 ///it will allocate one. The destructor deallocates this
557 ///automatically allocated map, of course.
558 ///\return <tt> (*this) </tt>
559 Dijkstra &distMap(DistMap &m)
569 ///Sets the heap and the cross reference used by algorithm.
571 ///Sets the heap and the cross reference used by algorithm.
572 ///If you don't use this function before calling \ref run(),
573 ///it will allocate one. The destructor deallocates this
574 ///automatically allocated heap and cross reference, of course.
575 ///\return <tt> (*this) </tt>
576 Dijkstra &heap(Heap& hp, HeapCrossRef &cr)
578 if(local_heap_cross_ref) {
579 delete _heap_cross_ref;
580 local_heap_cross_ref=false;
582 _heap_cross_ref = &cr;
593 void finalizeNodeData(Node v,Value dst)
595 _processed->set(v,true);
601 ///\name Execution control
602 ///The simplest way to execute the algorithm is to use one of the
603 ///member functions called \ref lemon::Dijkstra::run() "run()".
605 ///If you need more control on the execution, first you must call
606 ///\ref lemon::Dijkstra::init() "init()", then you can add several
607 ///source nodes with \ref lemon::Dijkstra::addSource() "addSource()".
608 ///Finally \ref lemon::Dijkstra::start() "start()" will perform the
609 ///actual path computation.
613 ///Initializes the internal data structures.
615 ///Initializes the internal data structures.
621 for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
622 _pred->set(u,INVALID);
623 _processed->set(u,false);
624 _heap_cross_ref->set(u,Heap::PRE_HEAP);
628 ///Adds a new source node.
630 ///Adds a new source node to the priority heap.
631 ///The optional second parameter is the initial distance of the node.
633 ///The function checks if the node has already been added to the heap and
634 ///it is pushed to the heap only if either it was not in the heap
635 ///or the shortest path found till then is shorter than \c dst.
636 void addSource(Node s,Value dst=OperationTraits::zero())
638 if(_heap->state(s) != Heap::IN_HEAP) {
640 } else if(OperationTraits::less((*_heap)[s], dst)) {
642 _pred->set(s,INVALID);
646 ///Processes the next node in the priority heap
648 ///Processes the next node in the priority heap.
650 ///\return The processed node.
652 ///\warning The priority heap must not be empty.
653 Node processNextNode()
656 Value oldvalue=_heap->prio();
658 finalizeNodeData(v,oldvalue);
660 for(OutArcIt e(*G,v); e!=INVALID; ++e) {
662 switch(_heap->state(w)) {
664 _heap->push(w,OperationTraits::plus(oldvalue, (*length)[e]));
669 Value newvalue = OperationTraits::plus(oldvalue, (*length)[e]);
670 if ( OperationTraits::less(newvalue, (*_heap)[w]) ) {
671 _heap->decrease(w, newvalue);
676 case Heap::POST_HEAP:
683 ///The next node to be processed.
685 ///Returns the next node to be processed or \c INVALID if the
686 ///priority heap is empty.
687 Node nextNode() const
689 return !_heap->empty()?_heap->top():INVALID;
692 ///\brief Returns \c false if there are nodes
695 ///Returns \c false if there are nodes
696 ///to be processed in the priority heap.
697 bool emptyQueue() const { return _heap->empty(); }
699 ///Returns the number of the nodes to be processed in the priority heap
701 ///Returns the number of the nodes to be processed in the priority heap.
703 int queueSize() const { return _heap->size(); }
705 ///Executes the algorithm.
707 ///Executes the algorithm.
709 ///This method runs the %Dijkstra algorithm from the root node(s)
710 ///in order to compute the shortest path to each node.
712 ///The algorithm computes
713 ///- the shortest path tree (forest),
714 ///- the distance of each node from the root(s).
716 ///\pre init() must be called and at least one root node should be
717 ///added with addSource() before using this function.
719 ///\note <tt>d.start()</tt> is just a shortcut of the following code.
721 /// while ( !d.emptyQueue() ) {
722 /// d.processNextNode();
727 while ( !emptyQueue() ) processNextNode();
730 ///Executes the algorithm until the given target node is reached.
732 ///Executes the algorithm until the given target node is reached.
734 ///This method runs the %Dijkstra algorithm from the root node(s)
735 ///in order to compute the shortest path to \c dest.
737 ///The algorithm computes
738 ///- the shortest path to \c dest,
739 ///- the distance of \c dest from the root(s).
741 ///\pre init() must be called and at least one root node should be
742 ///added with addSource() before using this function.
743 void start(Node dest)
745 while ( !_heap->empty() && _heap->top()!=dest ) processNextNode();
746 if ( !_heap->empty() ) finalizeNodeData(_heap->top(),_heap->prio());
749 ///Executes the algorithm until a condition is met.
751 ///Executes the algorithm until a condition is met.
753 ///This method runs the %Dijkstra algorithm from the root node(s) in
754 ///order to compute the shortest path to a node \c v with
755 /// <tt>nm[v]</tt> true, if such a node can be found.
757 ///\param nm A \c bool (or convertible) node map. The algorithm
758 ///will stop when it reaches a node \c v with <tt>nm[v]</tt> true.
760 ///\return The reached node \c v with <tt>nm[v]</tt> true or
761 ///\c INVALID if no such node was found.
763 ///\pre init() must be called and at least one root node should be
764 ///added with addSource() before using this function.
765 template<class NodeBoolMap>
766 Node start(const NodeBoolMap &nm)
768 while ( !_heap->empty() && !nm[_heap->top()] ) processNextNode();
769 if ( _heap->empty() ) return INVALID;
770 finalizeNodeData(_heap->top(),_heap->prio());
774 ///Runs the algorithm from the given node.
776 ///This method runs the %Dijkstra algorithm from node \c s
777 ///in order to compute the shortest path to each node.
779 ///The algorithm computes
780 ///- the shortest path tree,
781 ///- the distance of each node from the root.
783 ///\note <tt>d.run(s)</tt> is just a shortcut of the following code.
795 ///Finds the shortest path between \c s and \c t.
797 ///This method runs the %Dijkstra algorithm from node \c s
798 ///in order to compute the shortest path to \c t.
800 ///\return The length of the shortest <tt>s</tt>--<tt>t</tt> path,
801 ///if \c t is reachable form \c s, \c 0 otherwise.
803 ///\note Apart from the return value, <tt>d.run(s,t)</tt> is just a
804 ///shortcut of the following code.
810 Value run(Node s,Node t) {
814 return (*_pred)[t]==INVALID?OperationTraits::zero():(*_dist)[t];
819 ///\name Query Functions
820 ///The result of the %Dijkstra algorithm can be obtained using these
822 ///Either \ref lemon::Dijkstra::run() "run()" or
823 ///\ref lemon::Dijkstra::start() "start()" must be called before
828 ///The shortest path to a node.
830 ///Returns the shortest path to a node.
832 ///\warning \c t should be reachable from the root(s).
834 ///\pre Either \ref run() or \ref start() must be called before
835 ///using this function.
836 Path path(Node t) const { return Path(*G, *_pred, t); }
838 ///The distance of a node from the root(s).
840 ///Returns the distance of a node from the root(s).
842 ///\warning If node \c v is not reachable from the root(s), then
843 ///the return value of this function is undefined.
845 ///\pre Either \ref run() or \ref start() must be called before
846 ///using this function.
847 Value dist(Node v) const { return (*_dist)[v]; }
849 ///Returns the 'previous arc' of the shortest path tree for a node.
851 ///This function returns the 'previous arc' of the shortest path
852 ///tree for the node \c v, i.e. it returns the last arc of a
853 ///shortest path from the root(s) to \c v. It is \c INVALID if \c v
854 ///is not reachable from the root(s) or if \c v is a root.
856 ///The shortest path tree used here is equal to the shortest path
857 ///tree used in \ref predNode().
859 ///\pre Either \ref run() or \ref start() must be called before
860 ///using this function.
861 Arc predArc(Node v) const { return (*_pred)[v]; }
863 ///Returns the 'previous node' of the shortest path tree for a node.
865 ///This function returns the 'previous node' of the shortest path
866 ///tree for the node \c v, i.e. it returns the last but one node
867 ///from a shortest path from the root(s) to \c v. It is \c INVALID
868 ///if \c v is not reachable from the root(s) or if \c v is a root.
870 ///The shortest path tree used here is equal to the shortest path
871 ///tree used in \ref predArc().
873 ///\pre Either \ref run() or \ref start() must be called before
874 ///using this function.
875 Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
876 G->source((*_pred)[v]); }
878 ///\brief Returns a const reference to the node map that stores the
879 ///distances of the nodes.
881 ///Returns a const reference to the node map that stores the distances
882 ///of the nodes calculated by the algorithm.
884 ///\pre Either \ref run() or \ref init()
885 ///must be called before using this function.
886 const DistMap &distMap() const { return *_dist;}
888 ///\brief Returns a const reference to the node map that stores the
891 ///Returns a const reference to the node map that stores the predecessor
892 ///arcs, which form the shortest path tree.
894 ///\pre Either \ref run() or \ref init()
895 ///must be called before using this function.
896 const PredMap &predMap() const { return *_pred;}
898 ///Checks if a node is reachable from the root(s).
900 ///Returns \c true if \c v is reachable from the root(s).
901 ///\pre Either \ref run() or \ref start()
902 ///must be called before using this function.
903 bool reached(Node v) const { return (*_heap_cross_ref)[v] !=
906 ///Checks if a node is processed.
908 ///Returns \c true if \c v is processed, i.e. the shortest
909 ///path to \c v has already found.
910 ///\pre Either \ref run() or \ref start()
911 ///must be called before using this function.
912 bool processed(Node v) const { return (*_heap_cross_ref)[v] ==
915 ///The current distance of a node from the root(s).
917 ///Returns the current distance of a node from the root(s).
918 ///It may be decreased in the following processes.
919 ///\pre \c v should be reached but not processed.
920 Value currentDist(Node v) const { return (*_heap)[v]; }
926 ///Default traits class of dijkstra() function.
928 ///Default traits class of dijkstra() function.
929 ///\tparam GR The type of the digraph.
930 ///\tparam LM The type of the length map.
931 template<class GR, class LM>
932 struct DijkstraWizardDefaultTraits
934 ///The type of the digraph the algorithm runs on.
936 ///The type of the map that stores the arc lengths.
938 ///The type of the map that stores the arc lengths.
939 ///It must meet the \ref concepts::ReadMap "ReadMap" concept.
940 typedef LM LengthMap;
941 ///The type of the length of the arcs.
942 typedef typename LM::Value Value;
944 /// Operation traits for Dijkstra algorithm.
946 /// This class defines the operations that are used in the algorithm.
947 /// \see DijkstraDefaultOperationTraits
948 typedef DijkstraDefaultOperationTraits<Value> OperationTraits;
950 /// The cross reference type used by the heap.
952 /// The cross reference type used by the heap.
953 /// Usually it is \c Digraph::NodeMap<int>.
954 typedef typename Digraph::template NodeMap<int> HeapCrossRef;
955 ///Instantiates a \ref HeapCrossRef.
957 ///This function instantiates a \ref HeapCrossRef.
958 /// \param g is the digraph, to which we would like to define the
960 /// \todo The digraph alone may be insufficient for the initialization
961 static HeapCrossRef *createHeapCrossRef(const Digraph &g)
963 return new HeapCrossRef(g);
966 ///The heap type used by the Dijkstra algorithm.
968 ///The heap type used by the Dijkstra algorithm.
972 typedef BinHeap<Value, typename Digraph::template NodeMap<int>,
973 std::less<Value> > Heap;
975 ///Instantiates a \ref Heap.
977 ///This function instantiates a \ref Heap.
978 /// \param r is the HeapCrossRef which is used.
979 static Heap *createHeap(HeapCrossRef& r)
984 ///\brief The type of the map that stores the predecessor
985 ///arcs of the shortest paths.
987 ///The type of the map that stores the predecessor
988 ///arcs of the shortest paths.
989 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
990 typedef NullMap <typename Digraph::Node,typename Digraph::Arc> PredMap;
991 ///Instantiates a \ref PredMap.
993 ///This function instantiates a \ref PredMap.
994 ///\param g is the digraph, to which we would like to define the
996 ///\todo The digraph alone may be insufficient to initialize
998 static PredMap *createPredMap(const Digraph &g)
1000 static PredMap *createPredMap(const Digraph &)
1003 return new PredMap();
1006 ///The type of the map that indicates which nodes are processed.
1008 ///The type of the map that indicates which nodes are processed.
1009 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
1010 ///By default it is a NullMap.
1011 ///\todo If it is set to a real map,
1012 ///Dijkstra::processed() should read this.
1013 ///\todo named parameter to set this type, function to read and write.
1014 typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
1015 ///Instantiates a \ref ProcessedMap.
1017 ///This function instantiates a \ref ProcessedMap.
1018 ///\param g is the digraph, to which
1019 ///we would like to define the \ref ProcessedMap.
1021 static ProcessedMap *createProcessedMap(const Digraph &g)
1023 static ProcessedMap *createProcessedMap(const Digraph &)
1026 return new ProcessedMap();
1029 ///The type of the map that stores the distances of the nodes.
1031 ///The type of the map that stores the distances of the nodes.
1032 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
1033 typedef NullMap<typename Digraph::Node,Value> DistMap;
1034 ///Instantiates a \ref DistMap.
1036 ///This function instantiates a \ref DistMap.
1037 ///\param g is the digraph, to which we would like to define
1040 static DistMap *createDistMap(const Digraph &g)
1042 static DistMap *createDistMap(const Digraph &)
1045 return new DistMap();
1049 /// Default traits class used by \ref DijkstraWizard
1051 /// To make it easier to use Dijkstra algorithm
1052 /// we have created a wizard class.
1053 /// This \ref DijkstraWizard class needs default traits,
1054 /// as well as the \ref Dijkstra class.
1055 /// The \ref DijkstraWizardBase is a class to be the default traits of the
1056 /// \ref DijkstraWizard class.
1057 /// \todo More named parameters are required...
1058 template<class GR,class LM>
1059 class DijkstraWizardBase : public DijkstraWizardDefaultTraits<GR,LM>
1061 typedef DijkstraWizardDefaultTraits<GR,LM> Base;
1063 //The type of the nodes in the digraph.
1064 typedef typename Base::Digraph::Node Node;
1066 //Pointer to the digraph the algorithm runs on.
1068 //Pointer to the length map
1070 //Pointer to the map of processed nodes.
1072 //Pointer to the map of predecessors arcs.
1074 //Pointer to the map of distances.
1076 //Pointer to the source node.
1082 /// This constructor does not require parameters, therefore it initiates
1083 /// all of the attributes to default values (0, INVALID).
1084 DijkstraWizardBase() : _g(0), _length(0), _processed(0), _pred(0),
1085 _dist(0), _source(INVALID) {}
1089 /// This constructor requires some parameters,
1090 /// listed in the parameters list.
1091 /// Others are initiated to 0.
1092 /// \param g The digraph the algorithm runs on.
1093 /// \param l The length map.
1094 /// \param s The source node.
1095 DijkstraWizardBase(const GR &g,const LM &l, Node s=INVALID) :
1096 _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
1097 _length(reinterpret_cast<void*>(const_cast<LM*>(&l))),
1098 _processed(0), _pred(0), _dist(0), _source(s) {}
1102 /// Auxiliary class for the function type interface of Dijkstra algorithm.
1104 /// This auxiliary class is created to implement the function type
1105 /// interface of \ref Dijkstra algorithm. It uses the functions and features
1106 /// of the plain \ref Dijkstra, but it is much simpler to use it.
1107 /// It should only be used through the \ref dijkstra() function, which makes
1108 /// it easier to use the algorithm.
1110 /// Simplicity means that the way to change the types defined
1111 /// in the traits class is based on functions that returns the new class
1112 /// and not on templatable built-in classes.
1113 /// When using the plain \ref Dijkstra
1114 /// the new class with the modified type comes from
1115 /// the original class by using the ::
1116 /// operator. In the case of \ref DijkstraWizard only
1117 /// a function have to be called, and it will
1118 /// return the needed class.
1120 /// It does not have own \ref run() method. When its \ref run() method
1121 /// is called, it initiates a plain \ref Dijkstra object, and calls the
1122 /// \ref Dijkstra::run() method of it.
1124 class DijkstraWizard : public TR
1128 ///The type of the digraph the algorithm runs on.
1129 typedef typename TR::Digraph Digraph;
1131 typedef typename Digraph::Node Node;
1132 typedef typename Digraph::NodeIt NodeIt;
1133 typedef typename Digraph::Arc Arc;
1134 typedef typename Digraph::OutArcIt OutArcIt;
1136 ///The type of the map that stores the arc lengths.
1137 typedef typename TR::LengthMap LengthMap;
1138 ///The type of the length of the arcs.
1139 typedef typename LengthMap::Value Value;
1140 ///\brief The type of the map that stores the predecessor
1141 ///arcs of the shortest paths.
1142 typedef typename TR::PredMap PredMap;
1143 ///The type of the map that stores the distances of the nodes.
1144 typedef typename TR::DistMap DistMap;
1145 ///The type of the map that indicates which nodes are processed.
1146 typedef typename TR::ProcessedMap ProcessedMap;
1147 ///The heap type used by the dijkstra algorithm.
1148 typedef typename TR::Heap Heap;
1153 DijkstraWizard() : TR() {}
1155 /// Constructor that requires parameters.
1157 /// Constructor that requires parameters.
1158 /// These parameters will be the default values for the traits class.
1159 DijkstraWizard(const Digraph &g,const LengthMap &l, Node s=INVALID) :
1163 DijkstraWizard(const TR &b) : TR(b) {}
1165 ~DijkstraWizard() {}
1167 ///Runs Dijkstra algorithm from a source node.
1169 ///Runs Dijkstra algorithm from a source node.
1170 ///The node can be given with the \ref source() function.
1173 if(Base::_source==INVALID) throw UninitializedParameter();
1174 Dijkstra<Digraph,LengthMap,TR>
1175 dij(*reinterpret_cast<const Digraph*>(Base::_g),
1176 *reinterpret_cast<const LengthMap*>(Base::_length));
1177 if(Base::_processed)
1178 dij.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1180 dij.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1182 dij.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1183 dij.run(Base::_source);
1186 ///Runs Dijkstra algorithm from the given node.
1188 ///Runs Dijkstra algorithm from the given node.
1189 ///\param s is the given source.
1196 /// Sets the source node, from which the Dijkstra algorithm runs.
1198 /// Sets the source node, from which the Dijkstra algorithm runs.
1199 /// \param s is the source node.
1200 DijkstraWizard<TR> &source(Node s)
1207 struct SetPredMapBase : public Base {
1209 static PredMap *createPredMap(const Digraph &) { return 0; };
1210 SetPredMapBase(const TR &b) : TR(b) {}
1212 ///\brief \ref named-templ-param "Named parameter"
1213 ///for setting \ref PredMap object.
1215 ///\ref named-templ-param "Named parameter"
1216 ///for setting \ref PredMap object.
1218 DijkstraWizard<SetPredMapBase<T> > predMap(const T &t)
1220 Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1221 return DijkstraWizard<SetPredMapBase<T> >(*this);
1225 struct SetProcessedMapBase : public Base {
1226 typedef T ProcessedMap;
1227 static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
1228 SetProcessedMapBase(const TR &b) : TR(b) {}
1230 ///\brief \ref named-templ-param "Named parameter"
1231 ///for setting \ref ProcessedMap object.
1233 /// \ref named-templ-param "Named parameter"
1234 ///for setting \ref ProcessedMap object.
1236 DijkstraWizard<SetProcessedMapBase<T> > processedMap(const T &t)
1238 Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1239 return DijkstraWizard<SetProcessedMapBase<T> >(*this);
1243 struct SetDistMapBase : public Base {
1245 static DistMap *createDistMap(const Digraph &) { return 0; };
1246 SetDistMapBase(const TR &b) : TR(b) {}
1248 ///\brief \ref named-templ-param "Named parameter"
1249 ///for setting \ref DistMap object.
1251 ///\ref named-templ-param "Named parameter"
1252 ///for setting \ref DistMap object.
1254 DijkstraWizard<SetDistMapBase<T> > distMap(const T &t)
1256 Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1257 return DijkstraWizard<SetDistMapBase<T> >(*this);
1262 ///Function type interface for Dijkstra algorithm.
1264 /// \ingroup shortest_path
1265 ///Function type interface for Dijkstra algorithm.
1267 ///This function also has several
1268 ///\ref named-templ-func-param "named parameters",
1269 ///they are declared as the members of class \ref DijkstraWizard.
1271 ///example shows how to use these parameters.
1273 /// dijkstra(g,length,source).predMap(preds).run();
1275 ///\warning Don't forget to put the \ref DijkstraWizard::run() "run()"
1276 ///to the end of the parameter list.
1277 ///\sa DijkstraWizard
1279 template<class GR, class LM>
1280 DijkstraWizard<DijkstraWizardBase<GR,LM> >
1281 dijkstra(const GR &g,const LM &l,typename GR::Node s=INVALID)
1283 return DijkstraWizard<DijkstraWizardBase<GR,LM> >(g,l,s);
1286 } //END OF NAMESPACE LEMON