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 type is \ref ListDigraph.
183 ///\tparam LM A \ref concepts::ReadMap "readable" arc map that specifies
184 ///the lengths of the arcs.
185 ///It is read once for each arc, so the map may involve in
186 ///relatively time consuming process to compute the arc lengths if
187 ///it is necessary. The default map type is \ref
188 ///concepts::Digraph::ArcMap "GR::ArcMap<int>".
190 template <typename GR, typename LM, typename TR>
192 template <typename GR=ListDigraph,
193 typename LM=typename GR::template ArcMap<int>,
194 typename TR=DijkstraDefaultTraits<GR,LM> >
199 ///The type of the digraph the algorithm runs on.
200 typedef typename TR::Digraph Digraph;
202 ///The type of the length of the arcs.
203 typedef typename TR::LengthMap::Value Value;
204 ///The type of the map that stores the arc lengths.
205 typedef typename TR::LengthMap LengthMap;
206 ///\brief The type of the map that stores the predecessor arcs of the
208 typedef typename TR::PredMap PredMap;
209 ///The type of the map that stores the distances of the nodes.
210 typedef typename TR::DistMap DistMap;
211 ///The type of the map that indicates which nodes are processed.
212 typedef typename TR::ProcessedMap ProcessedMap;
213 ///The type of the paths.
214 typedef PredMapPath<Digraph, PredMap> Path;
215 ///The cross reference type used for the current heap.
216 typedef typename TR::HeapCrossRef HeapCrossRef;
217 ///The heap type used by the algorithm.
218 typedef typename TR::Heap Heap;
219 ///The operation traits class.
220 typedef typename TR::OperationTraits OperationTraits;
222 ///The \ref DijkstraDefaultTraits "traits class" of the algorithm.
227 typedef typename Digraph::Node Node;
228 typedef typename Digraph::NodeIt NodeIt;
229 typedef typename Digraph::Arc Arc;
230 typedef typename Digraph::OutArcIt OutArcIt;
232 //Pointer to the underlying digraph.
234 //Pointer to the length map.
235 const LengthMap *length;
236 //Pointer to the map of predecessors arcs.
238 //Indicates if _pred is locally allocated (true) or not.
240 //Pointer to the map of distances.
242 //Indicates if _dist is locally allocated (true) or not.
244 //Pointer to the map of processed status of the nodes.
245 ProcessedMap *_processed;
246 //Indicates if _processed is locally allocated (true) or not.
247 bool local_processed;
248 //Pointer to the heap cross references.
249 HeapCrossRef *_heap_cross_ref;
250 //Indicates if _heap_cross_ref is locally allocated (true) or not.
251 bool local_heap_cross_ref;
252 //Pointer to the heap.
254 //Indicates if _heap is locally allocated (true) or not.
257 //Creates the maps if necessary.
262 _pred = Traits::createPredMap(*G);
266 _dist = Traits::createDistMap(*G);
269 local_processed = true;
270 _processed = Traits::createProcessedMap(*G);
272 if (!_heap_cross_ref) {
273 local_heap_cross_ref = true;
274 _heap_cross_ref = Traits::createHeapCrossRef(*G);
278 _heap = Traits::createHeap(*_heap_cross_ref);
284 typedef Dijkstra Create;
286 ///\name Named template parameters
291 struct SetPredMapTraits : public Traits {
293 static PredMap *createPredMap(const Digraph &)
295 LEMON_ASSERT(false, "PredMap is not initialized");
296 return 0; // ignore warnings
299 ///\brief \ref named-templ-param "Named parameter" for setting
302 ///\ref named-templ-param "Named parameter" for setting
304 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
307 : public Dijkstra< Digraph, LengthMap, SetPredMapTraits<T> > {
308 typedef Dijkstra< Digraph, LengthMap, SetPredMapTraits<T> > Create;
312 struct SetDistMapTraits : public Traits {
314 static DistMap *createDistMap(const Digraph &)
316 LEMON_ASSERT(false, "DistMap is not initialized");
317 return 0; // ignore warnings
320 ///\brief \ref named-templ-param "Named parameter" for setting
323 ///\ref named-templ-param "Named parameter" for setting
325 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
328 : public Dijkstra< Digraph, LengthMap, SetDistMapTraits<T> > {
329 typedef Dijkstra< Digraph, LengthMap, SetDistMapTraits<T> > Create;
333 struct SetProcessedMapTraits : public Traits {
334 typedef T ProcessedMap;
335 static ProcessedMap *createProcessedMap(const Digraph &)
337 LEMON_ASSERT(false, "ProcessedMap is not initialized");
338 return 0; // ignore warnings
341 ///\brief \ref named-templ-param "Named parameter" for setting
342 ///ProcessedMap type.
344 ///\ref named-templ-param "Named parameter" for setting
345 ///ProcessedMap type.
346 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
348 struct SetProcessedMap
349 : public Dijkstra< Digraph, LengthMap, SetProcessedMapTraits<T> > {
350 typedef Dijkstra< Digraph, LengthMap, SetProcessedMapTraits<T> > Create;
353 struct SetStandardProcessedMapTraits : public Traits {
354 typedef typename Digraph::template NodeMap<bool> ProcessedMap;
355 static ProcessedMap *createProcessedMap(const Digraph &g)
357 return new ProcessedMap(g);
360 ///\brief \ref named-templ-param "Named parameter" for setting
361 ///ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
363 ///\ref named-templ-param "Named parameter" for setting
364 ///ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
365 ///If you don't set it explicitly, it will be automatically allocated.
366 struct SetStandardProcessedMap
367 : public Dijkstra< Digraph, LengthMap, SetStandardProcessedMapTraits > {
368 typedef Dijkstra< Digraph, LengthMap, SetStandardProcessedMapTraits >
372 template <class H, class CR>
373 struct SetHeapTraits : public Traits {
374 typedef CR HeapCrossRef;
376 static HeapCrossRef *createHeapCrossRef(const Digraph &) {
377 LEMON_ASSERT(false, "HeapCrossRef is not initialized");
378 return 0; // ignore warnings
380 static Heap *createHeap(HeapCrossRef &)
382 LEMON_ASSERT(false, "Heap is not initialized");
383 return 0; // ignore warnings
386 ///\brief \ref named-templ-param "Named parameter" for setting
387 ///heap and cross reference types
389 ///\ref named-templ-param "Named parameter" for setting heap and cross
390 ///reference types. If this named parameter is used, then external
391 ///heap and cross reference objects must be passed to the algorithm
392 ///using the \ref heap() function before calling \ref run(Node) "run()"
394 ///\sa SetStandardHeap
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 types with automatic allocation
416 ///\ref named-templ-param "Named parameter" for setting heap and cross
417 ///reference types with automatic allocation.
418 ///They should have standard constructor interfaces to be able to
419 ///automatically created by the algorithm (i.e. the digraph should be
420 ///passed to the constructor of the cross reference and the cross
421 ///reference should be passed to the constructor of the heap).
422 ///However external heap and cross reference objects could also be
423 ///passed to the algorithm using the \ref heap() function before
424 ///calling \ref run(Node) "run()" or \ref init().
426 template <class H, class CR = typename Digraph::template NodeMap<int> >
427 struct SetStandardHeap
428 : public Dijkstra< Digraph, LengthMap, SetStandardHeapTraits<H, CR> > {
429 typedef Dijkstra< Digraph, LengthMap, SetStandardHeapTraits<H, CR> >
434 struct SetOperationTraitsTraits : public Traits {
435 typedef T OperationTraits;
438 /// \brief \ref named-templ-param "Named parameter" for setting
439 ///\c OperationTraits type
441 ///\ref named-templ-param "Named parameter" for setting
442 ///\ref OperationTraits type.
444 struct SetOperationTraits
445 : public Dijkstra<Digraph, LengthMap, SetOperationTraitsTraits<T> > {
446 typedef Dijkstra<Digraph, LengthMap, SetOperationTraitsTraits<T> >
461 ///\param _g The digraph the algorithm runs on.
462 ///\param _length The length map used by the algorithm.
463 Dijkstra(const Digraph& _g, const LengthMap& _length) :
464 G(&_g), length(&_length),
465 _pred(NULL), local_pred(false),
466 _dist(NULL), local_dist(false),
467 _processed(NULL), local_processed(false),
468 _heap_cross_ref(NULL), local_heap_cross_ref(false),
469 _heap(NULL), local_heap(false)
475 if(local_pred) delete _pred;
476 if(local_dist) delete _dist;
477 if(local_processed) delete _processed;
478 if(local_heap_cross_ref) delete _heap_cross_ref;
479 if(local_heap) delete _heap;
482 ///Sets the length map.
484 ///Sets the length map.
485 ///\return <tt> (*this) </tt>
486 Dijkstra &lengthMap(const LengthMap &m)
492 ///Sets the map that stores the predecessor arcs.
494 ///Sets the map that stores the predecessor arcs.
495 ///If you don't use this function before calling \ref run(Node) "run()"
496 ///or \ref init(), an instance will be allocated automatically.
497 ///The destructor deallocates this automatically allocated map,
499 ///\return <tt> (*this) </tt>
500 Dijkstra &predMap(PredMap &m)
510 ///Sets the map that indicates which nodes are processed.
512 ///Sets the map that indicates which nodes are processed.
513 ///If you don't use this function before calling \ref run(Node) "run()"
514 ///or \ref init(), an instance will be allocated automatically.
515 ///The destructor deallocates this automatically allocated map,
517 ///\return <tt> (*this) </tt>
518 Dijkstra &processedMap(ProcessedMap &m)
520 if(local_processed) {
522 local_processed=false;
528 ///Sets the map that stores the distances of the nodes.
530 ///Sets the map that stores the distances of the nodes calculated by the
532 ///If you don't use this function before calling \ref run(Node) "run()"
533 ///or \ref init(), an instance will be allocated automatically.
534 ///The destructor deallocates this automatically allocated map,
536 ///\return <tt> (*this) </tt>
537 Dijkstra &distMap(DistMap &m)
547 ///Sets the heap and the cross reference used by algorithm.
549 ///Sets the heap and the cross reference used by algorithm.
550 ///If you don't use this function before calling \ref run(Node) "run()"
551 ///or \ref init(), heap and cross reference instances will be
552 ///allocated automatically.
553 ///The destructor deallocates these automatically allocated objects,
555 ///\return <tt> (*this) </tt>
556 Dijkstra &heap(Heap& hp, HeapCrossRef &cr)
558 if(local_heap_cross_ref) {
559 delete _heap_cross_ref;
560 local_heap_cross_ref=false;
562 _heap_cross_ref = &cr;
573 void finalizeNodeData(Node v,Value dst)
575 _processed->set(v,true);
581 ///\name Execution Control
582 ///The simplest way to execute the %Dijkstra algorithm is to use
583 ///one of the member functions called \ref run(Node) "run()".\n
584 ///If you need more control on the execution, first you have to call
585 ///\ref init(), then you can add several source nodes with
586 ///\ref addSource(). Finally the actual path computation can be
587 ///performed with one of the \ref start() functions.
591 ///\brief Initializes the internal data structures.
593 ///Initializes the internal data structures.
598 for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
599 _pred->set(u,INVALID);
600 _processed->set(u,false);
601 _heap_cross_ref->set(u,Heap::PRE_HEAP);
605 ///Adds a new source node.
607 ///Adds a new source node to the priority heap.
608 ///The optional second parameter is the initial distance of the node.
610 ///The function checks if the node has already been added to the heap and
611 ///it is pushed to the heap only if either it was not in the heap
612 ///or the shortest path found till then is shorter than \c dst.
613 void addSource(Node s,Value dst=OperationTraits::zero())
615 if(_heap->state(s) != Heap::IN_HEAP) {
617 } else if(OperationTraits::less((*_heap)[s], dst)) {
619 _pred->set(s,INVALID);
623 ///Processes the next node in the priority heap
625 ///Processes the next node in the priority heap.
627 ///\return The processed node.
629 ///\warning The priority heap must not be empty.
630 Node processNextNode()
633 Value oldvalue=_heap->prio();
635 finalizeNodeData(v,oldvalue);
637 for(OutArcIt e(*G,v); e!=INVALID; ++e) {
639 switch(_heap->state(w)) {
641 _heap->push(w,OperationTraits::plus(oldvalue, (*length)[e]));
646 Value newvalue = OperationTraits::plus(oldvalue, (*length)[e]);
647 if ( OperationTraits::less(newvalue, (*_heap)[w]) ) {
648 _heap->decrease(w, newvalue);
653 case Heap::POST_HEAP:
660 ///The next node to be processed.
662 ///Returns the next node to be processed or \c INVALID if the
663 ///priority heap is empty.
664 Node nextNode() const
666 return !_heap->empty()?_heap->top():INVALID;
669 ///Returns \c false if there are nodes to be processed.
671 ///Returns \c false if there are nodes to be processed
672 ///in the priority heap.
673 bool emptyQueue() const { return _heap->empty(); }
675 ///Returns the number of the nodes to be processed.
677 ///Returns the number of the nodes to be processed
678 ///in the priority heap.
679 int queueSize() const { return _heap->size(); }
681 ///Executes the algorithm.
683 ///Executes the algorithm.
685 ///This method runs the %Dijkstra algorithm from the root node(s)
686 ///in order to compute the shortest path to each node.
688 ///The algorithm computes
689 ///- the shortest path tree (forest),
690 ///- the distance of each node from the root(s).
692 ///\pre init() must be called and at least one root node should be
693 ///added with addSource() before using this function.
695 ///\note <tt>d.start()</tt> is just a shortcut of the following code.
697 /// while ( !d.emptyQueue() ) {
698 /// d.processNextNode();
703 while ( !emptyQueue() ) processNextNode();
706 ///Executes the algorithm until the given target node is processed.
708 ///Executes the algorithm until the given target node is processed.
710 ///This method runs the %Dijkstra algorithm from the root node(s)
711 ///in order to compute the shortest path to \c t.
713 ///The algorithm computes
714 ///- the shortest path to \c t,
715 ///- the distance of \c t from the root(s).
717 ///\pre init() must be called and at least one root node should be
718 ///added with addSource() before using this function.
721 while ( !_heap->empty() && _heap->top()!=t ) processNextNode();
722 if ( !_heap->empty() ) {
723 finalizeNodeData(_heap->top(),_heap->prio());
728 ///Executes the algorithm until a condition is met.
730 ///Executes the algorithm until a condition is met.
732 ///This method runs the %Dijkstra algorithm from the root node(s) in
733 ///order to compute the shortest path to a node \c v with
734 /// <tt>nm[v]</tt> true, if such a node can be found.
736 ///\param nm A \c bool (or convertible) node map. The algorithm
737 ///will stop when it reaches a node \c v with <tt>nm[v]</tt> true.
739 ///\return The reached node \c v with <tt>nm[v]</tt> true or
740 ///\c INVALID if no such node was found.
742 ///\pre init() must be called and at least one root node should be
743 ///added with addSource() before using this function.
744 template<class NodeBoolMap>
745 Node start(const NodeBoolMap &nm)
747 while ( !_heap->empty() && !nm[_heap->top()] ) processNextNode();
748 if ( _heap->empty() ) return INVALID;
749 finalizeNodeData(_heap->top(),_heap->prio());
753 ///Runs the algorithm from the given source node.
755 ///This method runs the %Dijkstra algorithm from node \c s
756 ///in order to compute the shortest path to each node.
758 ///The algorithm computes
759 ///- the shortest path tree,
760 ///- the distance of each node from the root.
762 ///\note <tt>d.run(s)</tt> is just a shortcut of the following code.
774 ///Finds the shortest path between \c s and \c t.
776 ///This method runs the %Dijkstra algorithm from node \c s
777 ///in order to compute the shortest path to node \c t
778 ///(it stops searching when \c t is processed).
780 ///\return \c true if \c t is reachable form \c s.
782 ///\note Apart from the return value, <tt>d.run(s,t)</tt> is just a
783 ///shortcut of the following code.
789 bool run(Node s,Node t) {
793 return (*_heap_cross_ref)[t] == Heap::POST_HEAP;
798 ///\name Query Functions
799 ///The results of the %Dijkstra algorithm can be obtained using these
801 ///Either \ref run(Node) "run()" or \ref start() should be called
802 ///before using them.
806 ///The shortest path to a node.
808 ///Returns the shortest path to a node.
810 ///\warning \c t should be reached from the root(s).
812 ///\pre Either \ref run(Node) "run()" or \ref init()
813 ///must be called before using this function.
814 Path path(Node t) const { return Path(*G, *_pred, t); }
816 ///The distance of a node from the root(s).
818 ///Returns the distance of a node from the root(s).
820 ///\warning If node \c v is not reached from the root(s), then
821 ///the return value of this function is undefined.
823 ///\pre Either \ref run(Node) "run()" or \ref init()
824 ///must be called before using this function.
825 Value dist(Node v) const { return (*_dist)[v]; }
827 ///Returns the 'previous arc' of the shortest path tree for a node.
829 ///This function returns the 'previous arc' of the shortest path
830 ///tree for the node \c v, i.e. it returns the last arc of a
831 ///shortest path from a root to \c v. It is \c INVALID if \c v
832 ///is not reached from the root(s) or if \c v is a root.
834 ///The shortest path tree used here is equal to the shortest path
835 ///tree used in \ref predNode().
837 ///\pre Either \ref run(Node) "run()" or \ref init()
838 ///must be called before using this function.
839 Arc predArc(Node v) const { return (*_pred)[v]; }
841 ///Returns the 'previous node' of the shortest path tree for a node.
843 ///This function returns the 'previous node' of the shortest path
844 ///tree for the node \c v, i.e. it returns the last but one node
845 ///from a shortest path from a root to \c v. It is \c INVALID
846 ///if \c v is not reached from the root(s) or if \c v is a root.
848 ///The shortest path tree used here is equal to the shortest path
849 ///tree used in \ref predArc().
851 ///\pre Either \ref run(Node) "run()" or \ref init()
852 ///must be called before using this function.
853 Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
854 G->source((*_pred)[v]); }
856 ///\brief Returns a const reference to the node map that stores the
857 ///distances of the nodes.
859 ///Returns a const reference to the node map that stores the distances
860 ///of the nodes calculated by the algorithm.
862 ///\pre Either \ref run(Node) "run()" or \ref init()
863 ///must be called before using this function.
864 const DistMap &distMap() const { return *_dist;}
866 ///\brief Returns a const reference to the node map that stores the
869 ///Returns a const reference to the node map that stores the predecessor
870 ///arcs, which form the shortest path tree.
872 ///\pre Either \ref run(Node) "run()" or \ref init()
873 ///must be called before using this function.
874 const PredMap &predMap() const { return *_pred;}
876 ///Checks if a node is reached from the root(s).
878 ///Returns \c true if \c v is reached from the root(s).
880 ///\pre Either \ref run(Node) "run()" or \ref init()
881 ///must be called before using this function.
882 bool reached(Node v) const { return (*_heap_cross_ref)[v] !=
885 ///Checks if a node is processed.
887 ///Returns \c true if \c v is processed, i.e. the shortest
888 ///path to \c v has already found.
890 ///\pre Either \ref run(Node) "run()" or \ref init()
891 ///must be called before using this function.
892 bool processed(Node v) const { return (*_heap_cross_ref)[v] ==
895 ///The current distance of a node from the root(s).
897 ///Returns the current distance of a node from the root(s).
898 ///It may be decreased in the following processes.
900 ///\pre Either \ref run(Node) "run()" or \ref init()
901 ///must be called before using this function and
902 ///node \c v must be reached but not necessarily processed.
903 Value currentDist(Node v) const {
904 return processed(v) ? (*_dist)[v] : (*_heap)[v];
911 ///Default traits class of dijkstra() function.
913 ///Default traits class of dijkstra() function.
914 ///\tparam GR The type of the digraph.
915 ///\tparam LM The type of the length map.
916 template<class GR, class LM>
917 struct DijkstraWizardDefaultTraits
919 ///The type of the digraph the algorithm runs on.
921 ///The type of the map that stores the arc lengths.
923 ///The type of the map that stores the arc lengths.
924 ///It must meet the \ref concepts::ReadMap "ReadMap" concept.
925 typedef LM LengthMap;
926 ///The type of the length of the arcs.
927 typedef typename LM::Value Value;
929 /// Operation traits for Dijkstra algorithm.
931 /// This class defines the operations that are used in the algorithm.
932 /// \see DijkstraDefaultOperationTraits
933 typedef DijkstraDefaultOperationTraits<Value> OperationTraits;
935 /// The cross reference type used by the heap.
937 /// The cross reference type used by the heap.
938 /// Usually it is \c Digraph::NodeMap<int>.
939 typedef typename Digraph::template NodeMap<int> HeapCrossRef;
940 ///Instantiates a \ref HeapCrossRef.
942 ///This function instantiates a \ref HeapCrossRef.
943 /// \param g is the digraph, to which we would like to define the
945 static HeapCrossRef *createHeapCrossRef(const Digraph &g)
947 return new HeapCrossRef(g);
950 ///The heap type used by the Dijkstra algorithm.
952 ///The heap type used by the Dijkstra algorithm.
956 typedef BinHeap<Value, typename Digraph::template NodeMap<int>,
957 std::less<Value> > Heap;
959 ///Instantiates a \ref Heap.
961 ///This function instantiates a \ref Heap.
962 /// \param r is the HeapCrossRef which is used.
963 static Heap *createHeap(HeapCrossRef& r)
968 ///\brief The type of the map that stores the predecessor
969 ///arcs of the shortest paths.
971 ///The type of the map that stores the predecessor
972 ///arcs of the shortest paths.
973 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
974 typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
975 ///Instantiates a PredMap.
977 ///This function instantiates a PredMap.
978 ///\param g is the digraph, to which we would like to define the
980 static PredMap *createPredMap(const Digraph &g)
982 return new PredMap(g);
985 ///The type of the map that indicates which nodes are processed.
987 ///The type of the map that indicates which nodes are processed.
988 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
989 ///By default it is a NullMap.
990 typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
991 ///Instantiates a ProcessedMap.
993 ///This function instantiates a ProcessedMap.
994 ///\param g is the digraph, to which
995 ///we would like to define the ProcessedMap.
997 static ProcessedMap *createProcessedMap(const Digraph &g)
999 static ProcessedMap *createProcessedMap(const Digraph &)
1002 return new ProcessedMap();
1005 ///The type of the map that stores the distances of the nodes.
1007 ///The type of the map that stores the distances of the nodes.
1008 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
1009 typedef typename Digraph::template NodeMap<typename LM::Value> DistMap;
1010 ///Instantiates a DistMap.
1012 ///This function instantiates a DistMap.
1013 ///\param g is the digraph, to which we would like to define
1015 static DistMap *createDistMap(const Digraph &g)
1017 return new DistMap(g);
1020 ///The type of the shortest paths.
1022 ///The type of the shortest paths.
1023 ///It must meet the \ref concepts::Path "Path" concept.
1024 typedef lemon::Path<Digraph> Path;
1027 /// Default traits class used by DijkstraWizard
1029 /// To make it easier to use Dijkstra algorithm
1030 /// we have created a wizard class.
1031 /// This \ref DijkstraWizard class needs default traits,
1032 /// as well as the \ref Dijkstra class.
1033 /// The \ref DijkstraWizardBase is a class to be the default traits of the
1034 /// \ref DijkstraWizard class.
1035 template<class GR,class LM>
1036 class DijkstraWizardBase : public DijkstraWizardDefaultTraits<GR,LM>
1038 typedef DijkstraWizardDefaultTraits<GR,LM> Base;
1040 //The type of the nodes in the digraph.
1041 typedef typename Base::Digraph::Node Node;
1043 //Pointer to the digraph the algorithm runs on.
1045 //Pointer to the length map.
1047 //Pointer to the map of processed nodes.
1049 //Pointer to the map of predecessors arcs.
1051 //Pointer to the map of distances.
1053 //Pointer to the shortest path to the target node.
1055 //Pointer to the distance of the target node.
1061 /// This constructor does not require parameters, therefore it initiates
1062 /// all of the attributes to \c 0.
1063 DijkstraWizardBase() : _g(0), _length(0), _processed(0), _pred(0),
1064 _dist(0), _path(0), _di(0) {}
1068 /// This constructor requires two parameters,
1069 /// others are initiated to \c 0.
1070 /// \param g The digraph the algorithm runs on.
1071 /// \param l The length map.
1072 DijkstraWizardBase(const GR &g,const LM &l) :
1073 _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
1074 _length(reinterpret_cast<void*>(const_cast<LM*>(&l))),
1075 _processed(0), _pred(0), _dist(0), _path(0), _di(0) {}
1079 /// Auxiliary class for the function-type interface of Dijkstra algorithm.
1081 /// This auxiliary class is created to implement the
1082 /// \ref dijkstra() "function-type interface" of \ref Dijkstra algorithm.
1083 /// It does not have own \ref run(Node) "run()" method, it uses the
1084 /// functions and features of the plain \ref Dijkstra.
1086 /// This class should only be used through the \ref dijkstra() function,
1087 /// which makes it easier to use the algorithm.
1089 class DijkstraWizard : public TR
1093 ///The type of the digraph the algorithm runs on.
1094 typedef typename TR::Digraph Digraph;
1096 typedef typename Digraph::Node Node;
1097 typedef typename Digraph::NodeIt NodeIt;
1098 typedef typename Digraph::Arc Arc;
1099 typedef typename Digraph::OutArcIt OutArcIt;
1101 ///The type of the map that stores the arc lengths.
1102 typedef typename TR::LengthMap LengthMap;
1103 ///The type of the length of the arcs.
1104 typedef typename LengthMap::Value Value;
1105 ///\brief The type of the map that stores the predecessor
1106 ///arcs of the shortest paths.
1107 typedef typename TR::PredMap PredMap;
1108 ///The type of the map that stores the distances of the nodes.
1109 typedef typename TR::DistMap DistMap;
1110 ///The type of the map that indicates which nodes are processed.
1111 typedef typename TR::ProcessedMap ProcessedMap;
1112 ///The type of the shortest paths
1113 typedef typename TR::Path Path;
1114 ///The heap type used by the dijkstra algorithm.
1115 typedef typename TR::Heap Heap;
1120 DijkstraWizard() : TR() {}
1122 /// Constructor that requires parameters.
1124 /// Constructor that requires parameters.
1125 /// These parameters will be the default values for the traits class.
1126 /// \param g The digraph the algorithm runs on.
1127 /// \param l The length map.
1128 DijkstraWizard(const Digraph &g, const LengthMap &l) :
1132 DijkstraWizard(const TR &b) : TR(b) {}
1134 ~DijkstraWizard() {}
1136 ///Runs Dijkstra algorithm from the given source node.
1138 ///This method runs %Dijkstra algorithm from the given source node
1139 ///in order to compute the shortest path to each node.
1142 Dijkstra<Digraph,LengthMap,TR>
1143 dijk(*reinterpret_cast<const Digraph*>(Base::_g),
1144 *reinterpret_cast<const LengthMap*>(Base::_length));
1146 dijk.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1148 dijk.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1149 if (Base::_processed)
1150 dijk.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1154 ///Finds the shortest path between \c s and \c t.
1156 ///This method runs the %Dijkstra algorithm from node \c s
1157 ///in order to compute the shortest path to node \c t
1158 ///(it stops searching when \c t is processed).
1160 ///\return \c true if \c t is reachable form \c s.
1161 bool run(Node s, Node t)
1163 Dijkstra<Digraph,LengthMap,TR>
1164 dijk(*reinterpret_cast<const Digraph*>(Base::_g),
1165 *reinterpret_cast<const LengthMap*>(Base::_length));
1167 dijk.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1169 dijk.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1170 if (Base::_processed)
1171 dijk.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1174 *reinterpret_cast<Path*>(Base::_path) = dijk.path(t);
1176 *reinterpret_cast<Value*>(Base::_di) = dijk.dist(t);
1177 return dijk.reached(t);
1181 struct SetPredMapBase : public Base {
1183 static PredMap *createPredMap(const Digraph &) { return 0; };
1184 SetPredMapBase(const TR &b) : TR(b) {}
1186 ///\brief \ref named-func-param "Named parameter"
1187 ///for setting PredMap object.
1189 ///\ref named-func-param "Named parameter"
1190 ///for setting PredMap object.
1192 DijkstraWizard<SetPredMapBase<T> > predMap(const T &t)
1194 Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1195 return DijkstraWizard<SetPredMapBase<T> >(*this);
1199 struct SetDistMapBase : public Base {
1201 static DistMap *createDistMap(const Digraph &) { return 0; };
1202 SetDistMapBase(const TR &b) : TR(b) {}
1204 ///\brief \ref named-func-param "Named parameter"
1205 ///for setting DistMap object.
1207 ///\ref named-func-param "Named parameter"
1208 ///for setting DistMap object.
1210 DijkstraWizard<SetDistMapBase<T> > distMap(const T &t)
1212 Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1213 return DijkstraWizard<SetDistMapBase<T> >(*this);
1217 struct SetProcessedMapBase : public Base {
1218 typedef T ProcessedMap;
1219 static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
1220 SetProcessedMapBase(const TR &b) : TR(b) {}
1222 ///\brief \ref named-func-param "Named parameter"
1223 ///for setting ProcessedMap object.
1225 /// \ref named-func-param "Named parameter"
1226 ///for setting ProcessedMap object.
1228 DijkstraWizard<SetProcessedMapBase<T> > processedMap(const T &t)
1230 Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1231 return DijkstraWizard<SetProcessedMapBase<T> >(*this);
1235 struct SetPathBase : public Base {
1237 SetPathBase(const TR &b) : TR(b) {}
1239 ///\brief \ref named-func-param "Named parameter"
1240 ///for getting the shortest path to the target node.
1242 ///\ref named-func-param "Named parameter"
1243 ///for getting the shortest path to the target node.
1245 DijkstraWizard<SetPathBase<T> > path(const T &t)
1247 Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t));
1248 return DijkstraWizard<SetPathBase<T> >(*this);
1251 ///\brief \ref named-func-param "Named parameter"
1252 ///for getting the distance of the target node.
1254 ///\ref named-func-param "Named parameter"
1255 ///for getting the distance of the target node.
1256 DijkstraWizard dist(const Value &d)
1258 Base::_di=reinterpret_cast<void*>(const_cast<Value*>(&d));
1264 ///Function-type interface for Dijkstra algorithm.
1266 /// \ingroup shortest_path
1267 ///Function-type interface for Dijkstra algorithm.
1269 ///This function also has several \ref named-func-param "named parameters",
1270 ///they are declared as the members of class \ref DijkstraWizard.
1271 ///The following examples show how to use these parameters.
1273 /// // Compute shortest path from node s to each node
1274 /// dijkstra(g,length).predMap(preds).distMap(dists).run(s);
1276 /// // Compute shortest path from s to t
1277 /// bool reached = dijkstra(g,length).path(p).dist(d).run(s,t);
1279 ///\warning Don't forget to put the \ref DijkstraWizard::run(Node) "run()"
1280 ///to the end of the parameter list.
1281 ///\sa DijkstraWizard
1283 template<class GR, class LM>
1284 DijkstraWizard<DijkstraWizardBase<GR,LM> >
1285 dijkstra(const GR &digraph, const LM &length)
1287 return DijkstraWizard<DijkstraWizardBase<GR,LM> >(digraph,length);
1290 } //END OF NAMESPACE LEMON