1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
3 * This file is a part of LEMON, a generic C++ optimization library.
5 * Copyright (C) 2003-2009
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.
42 struct DijkstraDefaultOperationTraits {
45 /// \brief Gives back the zero value of the type.
47 return static_cast<Value>(0);
49 /// \brief Gives back the sum of the given two elements.
50 static Value plus(const Value& left, const Value& right) {
53 /// \brief Gives back true only if the first value is less than the second.
54 static bool less(const Value& left, const Value& right) {
59 ///Default traits class of Dijkstra class.
61 ///Default traits class of Dijkstra class.
62 ///\tparam GR The type of the digraph.
63 ///\tparam LEN The type of the length map.
64 template<typename GR, typename LEN>
65 struct DijkstraDefaultTraits
67 ///The type of the digraph the algorithm runs on.
70 ///The type of the map that stores the arc lengths.
72 ///The type of the map that stores the arc lengths.
73 ///It must meet the \ref concepts::ReadMap "ReadMap" concept.
74 typedef LEN LengthMap;
75 ///The type of the length of the arcs.
76 typedef typename LEN::Value Value;
78 /// Operation traits for %Dijkstra algorithm.
80 /// This class defines the operations that are used in the algorithm.
81 /// \see DijkstraDefaultOperationTraits
82 typedef DijkstraDefaultOperationTraits<Value> OperationTraits;
84 /// The cross reference type used by the heap.
86 /// The cross reference type used by the heap.
87 /// Usually it is \c Digraph::NodeMap<int>.
88 typedef typename Digraph::template NodeMap<int> HeapCrossRef;
89 ///Instantiates a \c HeapCrossRef.
91 ///This function instantiates a \ref HeapCrossRef.
92 /// \param g is the digraph, to which we would like to define the
93 /// \ref HeapCrossRef.
94 static HeapCrossRef *createHeapCrossRef(const Digraph &g)
96 return new HeapCrossRef(g);
99 ///The heap type used by the %Dijkstra algorithm.
101 ///The heap type used by the Dijkstra algorithm.
105 typedef BinHeap<typename LEN::Value, HeapCrossRef, std::less<Value> > Heap;
106 ///Instantiates a \c Heap.
108 ///This function instantiates a \ref Heap.
109 static Heap *createHeap(HeapCrossRef& r)
114 ///\brief The type of the map that stores the predecessor
115 ///arcs of the shortest paths.
117 ///The type of the map that stores the predecessor
118 ///arcs of the shortest paths.
119 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
120 typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
121 ///Instantiates a \c PredMap.
123 ///This function instantiates a \ref PredMap.
124 ///\param g is the digraph, to which we would like to define the
126 static PredMap *createPredMap(const Digraph &g)
128 return new PredMap(g);
131 ///The type of the map that indicates which nodes are processed.
133 ///The type of the map that indicates which nodes are processed.
134 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
135 ///By default it is a NullMap.
136 typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
137 ///Instantiates a \c ProcessedMap.
139 ///This function instantiates a \ref ProcessedMap.
140 ///\param g is the digraph, to which
141 ///we would like to define the \ref ProcessedMap.
143 static ProcessedMap *createProcessedMap(const Digraph &g)
145 static ProcessedMap *createProcessedMap(const Digraph &)
148 return new ProcessedMap();
151 ///The type of the map that stores the distances of the nodes.
153 ///The type of the map that stores the distances of the nodes.
154 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
155 typedef typename Digraph::template NodeMap<typename LEN::Value> DistMap;
156 ///Instantiates a \c DistMap.
158 ///This function instantiates a \ref DistMap.
159 ///\param g is the digraph, to which we would like to define
161 static DistMap *createDistMap(const Digraph &g)
163 return new DistMap(g);
167 ///%Dijkstra algorithm class.
169 /// \ingroup shortest_path
170 ///This class provides an efficient implementation of the %Dijkstra algorithm.
172 ///The arc lengths are passed to the algorithm using a
173 ///\ref concepts::ReadMap "ReadMap",
174 ///so it is easy to change it to any kind of length.
175 ///The type of the length is determined by the
176 ///\ref concepts::ReadMap::Value "Value" of the length map.
177 ///It is also possible to change the underlying priority heap.
179 ///There is also a \ref dijkstra() "function-type interface" for the
180 ///%Dijkstra algorithm, which is convenient in the simplier cases and
181 ///it can be used easier.
183 ///\tparam GR The type of the digraph the algorithm runs on.
184 ///The default type is \ref ListDigraph.
185 ///\tparam LEN A \ref concepts::ReadMap "readable" arc map that specifies
186 ///the lengths of the arcs.
187 ///It is read once for each arc, so the map may involve in
188 ///relatively time consuming process to compute the arc lengths if
189 ///it is necessary. The default map type is \ref
190 ///concepts::Digraph::ArcMap "GR::ArcMap<int>".
192 template <typename GR, typename LEN, typename TR>
194 template <typename GR=ListDigraph,
195 typename LEN=typename GR::template ArcMap<int>,
196 typename TR=DijkstraDefaultTraits<GR,LEN> >
201 ///The type of the digraph the algorithm runs on.
202 typedef typename TR::Digraph Digraph;
204 ///The type of the length of the arcs.
205 typedef typename TR::LengthMap::Value Value;
206 ///The type of the map that stores the arc lengths.
207 typedef typename TR::LengthMap LengthMap;
208 ///\brief The type of the map that stores the predecessor arcs of the
210 typedef typename TR::PredMap PredMap;
211 ///The type of the map that stores the distances of the nodes.
212 typedef typename TR::DistMap DistMap;
213 ///The type of the map that indicates which nodes are processed.
214 typedef typename TR::ProcessedMap ProcessedMap;
215 ///The type of the paths.
216 typedef PredMapPath<Digraph, PredMap> Path;
217 ///The cross reference type used for the current heap.
218 typedef typename TR::HeapCrossRef HeapCrossRef;
219 ///The heap type used by the algorithm.
220 typedef typename TR::Heap Heap;
221 ///\brief The \ref DijkstraDefaultOperationTraits "operation traits class"
223 typedef typename TR::OperationTraits OperationTraits;
225 ///The \ref DijkstraDefaultTraits "traits class" of the algorithm.
230 typedef typename Digraph::Node Node;
231 typedef typename Digraph::NodeIt NodeIt;
232 typedef typename Digraph::Arc Arc;
233 typedef typename Digraph::OutArcIt OutArcIt;
235 //Pointer to the underlying digraph.
237 //Pointer to the length map.
238 const LengthMap *_length;
239 //Pointer to the map of predecessors arcs.
241 //Indicates if _pred is locally allocated (true) or not.
243 //Pointer to the map of distances.
245 //Indicates if _dist is locally allocated (true) or not.
247 //Pointer to the map of processed status of the nodes.
248 ProcessedMap *_processed;
249 //Indicates if _processed is locally allocated (true) or not.
250 bool local_processed;
251 //Pointer to the heap cross references.
252 HeapCrossRef *_heap_cross_ref;
253 //Indicates if _heap_cross_ref is locally allocated (true) or not.
254 bool local_heap_cross_ref;
255 //Pointer to the heap.
257 //Indicates if _heap is locally allocated (true) or not.
260 //Creates the maps if necessary.
265 _pred = Traits::createPredMap(*G);
269 _dist = Traits::createDistMap(*G);
272 local_processed = true;
273 _processed = Traits::createProcessedMap(*G);
275 if (!_heap_cross_ref) {
276 local_heap_cross_ref = true;
277 _heap_cross_ref = Traits::createHeapCrossRef(*G);
281 _heap = Traits::createHeap(*_heap_cross_ref);
287 typedef Dijkstra Create;
289 ///\name Named Template Parameters
294 struct SetPredMapTraits : public Traits {
296 static PredMap *createPredMap(const Digraph &)
298 LEMON_ASSERT(false, "PredMap is not initialized");
299 return 0; // ignore warnings
302 ///\brief \ref named-templ-param "Named parameter" for setting
305 ///\ref named-templ-param "Named parameter" for setting
307 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
310 : public Dijkstra< Digraph, LengthMap, SetPredMapTraits<T> > {
311 typedef Dijkstra< Digraph, LengthMap, SetPredMapTraits<T> > Create;
315 struct SetDistMapTraits : public Traits {
317 static DistMap *createDistMap(const Digraph &)
319 LEMON_ASSERT(false, "DistMap is not initialized");
320 return 0; // ignore warnings
323 ///\brief \ref named-templ-param "Named parameter" for setting
326 ///\ref named-templ-param "Named parameter" for setting
328 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
331 : public Dijkstra< Digraph, LengthMap, SetDistMapTraits<T> > {
332 typedef Dijkstra< Digraph, LengthMap, SetDistMapTraits<T> > Create;
336 struct SetProcessedMapTraits : public Traits {
337 typedef T ProcessedMap;
338 static ProcessedMap *createProcessedMap(const Digraph &)
340 LEMON_ASSERT(false, "ProcessedMap is not initialized");
341 return 0; // ignore warnings
344 ///\brief \ref named-templ-param "Named parameter" for setting
345 ///\c ProcessedMap type.
347 ///\ref named-templ-param "Named parameter" for setting
348 ///\c ProcessedMap type.
349 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
351 struct SetProcessedMap
352 : public Dijkstra< Digraph, LengthMap, SetProcessedMapTraits<T> > {
353 typedef Dijkstra< Digraph, LengthMap, SetProcessedMapTraits<T> > Create;
356 struct SetStandardProcessedMapTraits : public Traits {
357 typedef typename Digraph::template NodeMap<bool> ProcessedMap;
358 static ProcessedMap *createProcessedMap(const Digraph &g)
360 return new ProcessedMap(g);
363 ///\brief \ref named-templ-param "Named parameter" for setting
364 ///\c ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
366 ///\ref named-templ-param "Named parameter" for setting
367 ///\c ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
368 ///If you don't set it explicitly, it will be automatically allocated.
369 struct SetStandardProcessedMap
370 : public Dijkstra< Digraph, LengthMap, SetStandardProcessedMapTraits > {
371 typedef Dijkstra< Digraph, LengthMap, SetStandardProcessedMapTraits >
375 template <class H, class CR>
376 struct SetHeapTraits : public Traits {
377 typedef CR HeapCrossRef;
379 static HeapCrossRef *createHeapCrossRef(const Digraph &) {
380 LEMON_ASSERT(false, "HeapCrossRef is not initialized");
381 return 0; // ignore warnings
383 static Heap *createHeap(HeapCrossRef &)
385 LEMON_ASSERT(false, "Heap is not initialized");
386 return 0; // ignore warnings
389 ///\brief \ref named-templ-param "Named parameter" for setting
390 ///heap and cross reference types
392 ///\ref named-templ-param "Named parameter" for setting heap and cross
393 ///reference types. If this named parameter is used, then external
394 ///heap and cross reference objects must be passed to the algorithm
395 ///using the \ref heap() function before calling \ref run(Node) "run()"
397 ///\sa SetStandardHeap
398 template <class H, class CR = typename Digraph::template NodeMap<int> >
400 : public Dijkstra< Digraph, LengthMap, SetHeapTraits<H, CR> > {
401 typedef Dijkstra< Digraph, LengthMap, SetHeapTraits<H, CR> > Create;
404 template <class H, class CR>
405 struct SetStandardHeapTraits : public Traits {
406 typedef CR HeapCrossRef;
408 static HeapCrossRef *createHeapCrossRef(const Digraph &G) {
409 return new HeapCrossRef(G);
411 static Heap *createHeap(HeapCrossRef &R)
416 ///\brief \ref named-templ-param "Named parameter" for setting
417 ///heap and cross reference types with automatic allocation
419 ///\ref named-templ-param "Named parameter" for setting heap and cross
420 ///reference types with automatic allocation.
421 ///They should have standard constructor interfaces to be able to
422 ///automatically created by the algorithm (i.e. the digraph should be
423 ///passed to the constructor of the cross reference and the cross
424 ///reference should be passed to the constructor of the heap).
425 ///However external heap and cross reference objects could also be
426 ///passed to the algorithm using the \ref heap() function before
427 ///calling \ref run(Node) "run()" or \ref init().
429 template <class H, class CR = typename Digraph::template NodeMap<int> >
430 struct SetStandardHeap
431 : public Dijkstra< Digraph, LengthMap, SetStandardHeapTraits<H, CR> > {
432 typedef Dijkstra< Digraph, LengthMap, SetStandardHeapTraits<H, CR> >
437 struct SetOperationTraitsTraits : public Traits {
438 typedef T OperationTraits;
441 /// \brief \ref named-templ-param "Named parameter" for setting
442 ///\c OperationTraits type
444 ///\ref named-templ-param "Named parameter" for setting
445 ///\c OperationTraits type.
447 struct SetOperationTraits
448 : public Dijkstra<Digraph, LengthMap, SetOperationTraitsTraits<T> > {
449 typedef Dijkstra<Digraph, LengthMap, SetOperationTraitsTraits<T> >
464 ///\param g The digraph the algorithm runs on.
465 ///\param length The length map used by the algorithm.
466 Dijkstra(const Digraph& g, const LengthMap& length) :
467 G(&g), _length(&length),
468 _pred(NULL), local_pred(false),
469 _dist(NULL), local_dist(false),
470 _processed(NULL), local_processed(false),
471 _heap_cross_ref(NULL), local_heap_cross_ref(false),
472 _heap(NULL), local_heap(false)
478 if(local_pred) delete _pred;
479 if(local_dist) delete _dist;
480 if(local_processed) delete _processed;
481 if(local_heap_cross_ref) delete _heap_cross_ref;
482 if(local_heap) delete _heap;
485 ///Sets the length map.
487 ///Sets the length map.
488 ///\return <tt> (*this) </tt>
489 Dijkstra &lengthMap(const LengthMap &m)
495 ///Sets the map that stores the predecessor arcs.
497 ///Sets the map that stores the predecessor arcs.
498 ///If you don't use this function before calling \ref run(Node) "run()"
499 ///or \ref init(), an instance will be allocated automatically.
500 ///The destructor deallocates this automatically allocated map,
502 ///\return <tt> (*this) </tt>
503 Dijkstra &predMap(PredMap &m)
513 ///Sets the map that indicates which nodes are processed.
515 ///Sets the map that indicates which nodes are processed.
516 ///If you don't use this function before calling \ref run(Node) "run()"
517 ///or \ref init(), an instance will be allocated automatically.
518 ///The destructor deallocates this automatically allocated map,
520 ///\return <tt> (*this) </tt>
521 Dijkstra &processedMap(ProcessedMap &m)
523 if(local_processed) {
525 local_processed=false;
531 ///Sets the map that stores the distances of the nodes.
533 ///Sets the map that stores the distances of the nodes calculated by the
535 ///If you don't use this function before calling \ref run(Node) "run()"
536 ///or \ref init(), an instance will be allocated automatically.
537 ///The destructor deallocates this automatically allocated map,
539 ///\return <tt> (*this) </tt>
540 Dijkstra &distMap(DistMap &m)
550 ///Sets the heap and the cross reference used by algorithm.
552 ///Sets the heap and the cross reference used by algorithm.
553 ///If you don't use this function before calling \ref run(Node) "run()"
554 ///or \ref init(), heap and cross reference instances will be
555 ///allocated automatically.
556 ///The destructor deallocates these automatically allocated objects,
558 ///\return <tt> (*this) </tt>
559 Dijkstra &heap(Heap& hp, HeapCrossRef &cr)
561 if(local_heap_cross_ref) {
562 delete _heap_cross_ref;
563 local_heap_cross_ref=false;
565 _heap_cross_ref = &cr;
576 void finalizeNodeData(Node v,Value dst)
578 _processed->set(v,true);
584 ///\name Execution Control
585 ///The simplest way to execute the %Dijkstra algorithm is to use
586 ///one of the member functions called \ref run(Node) "run()".\n
587 ///If you need more control on the execution, first you have to call
588 ///\ref init(), then you can add several source nodes with
589 ///\ref addSource(). Finally the actual path computation can be
590 ///performed with one of the \ref start() functions.
594 ///\brief Initializes the internal data structures.
596 ///Initializes the internal data structures.
601 for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
602 _pred->set(u,INVALID);
603 _processed->set(u,false);
604 _heap_cross_ref->set(u,Heap::PRE_HEAP);
608 ///Adds a new source node.
610 ///Adds a new source node to the priority heap.
611 ///The optional second parameter is the initial distance of the node.
613 ///The function checks if the node has already been added to the heap and
614 ///it is pushed to the heap only if either it was not in the heap
615 ///or the shortest path found till then is shorter than \c dst.
616 void addSource(Node s,Value dst=OperationTraits::zero())
618 if(_heap->state(s) != Heap::IN_HEAP) {
620 } else if(OperationTraits::less((*_heap)[s], dst)) {
622 _pred->set(s,INVALID);
626 ///Processes the next node in the priority heap
628 ///Processes the next node in the priority heap.
630 ///\return The processed node.
632 ///\warning The priority heap must not be empty.
633 Node processNextNode()
636 Value oldvalue=_heap->prio();
638 finalizeNodeData(v,oldvalue);
640 for(OutArcIt e(*G,v); e!=INVALID; ++e) {
642 switch(_heap->state(w)) {
644 _heap->push(w,OperationTraits::plus(oldvalue, (*_length)[e]));
649 Value newvalue = OperationTraits::plus(oldvalue, (*_length)[e]);
650 if ( OperationTraits::less(newvalue, (*_heap)[w]) ) {
651 _heap->decrease(w, newvalue);
656 case Heap::POST_HEAP:
663 ///The next node to be processed.
665 ///Returns the next node to be processed or \c INVALID if the
666 ///priority heap is empty.
667 Node nextNode() const
669 return !_heap->empty()?_heap->top():INVALID;
672 ///Returns \c false if there are nodes to be processed.
674 ///Returns \c false if there are nodes to be processed
675 ///in the priority heap.
676 bool emptyQueue() const { return _heap->empty(); }
678 ///Returns the number of the nodes to be processed.
680 ///Returns the number of the nodes to be processed
681 ///in the priority heap.
682 int queueSize() const { return _heap->size(); }
684 ///Executes the algorithm.
686 ///Executes the algorithm.
688 ///This method runs the %Dijkstra algorithm from the root node(s)
689 ///in order to compute the shortest path to each node.
691 ///The algorithm computes
692 ///- the shortest path tree (forest),
693 ///- the distance of each node from the root(s).
695 ///\pre init() must be called and at least one root node should be
696 ///added with addSource() before using this function.
698 ///\note <tt>d.start()</tt> is just a shortcut of the following code.
700 /// while ( !d.emptyQueue() ) {
701 /// d.processNextNode();
706 while ( !emptyQueue() ) processNextNode();
709 ///Executes the algorithm until the given target node is processed.
711 ///Executes the algorithm until the given target node is processed.
713 ///This method runs the %Dijkstra algorithm from the root node(s)
714 ///in order to compute the shortest path to \c t.
716 ///The algorithm computes
717 ///- the shortest path to \c t,
718 ///- the distance of \c t from the root(s).
720 ///\pre init() must be called and at least one root node should be
721 ///added with addSource() before using this function.
724 while ( !_heap->empty() && _heap->top()!=t ) processNextNode();
725 if ( !_heap->empty() ) {
726 finalizeNodeData(_heap->top(),_heap->prio());
731 ///Executes the algorithm until a condition is met.
733 ///Executes the algorithm until a condition is met.
735 ///This method runs the %Dijkstra algorithm from the root node(s) in
736 ///order to compute the shortest path to a node \c v with
737 /// <tt>nm[v]</tt> true, if such a node can be found.
739 ///\param nm A \c bool (or convertible) node map. The algorithm
740 ///will stop when it reaches a node \c v with <tt>nm[v]</tt> true.
742 ///\return The reached node \c v with <tt>nm[v]</tt> true or
743 ///\c INVALID if no such node was found.
745 ///\pre init() must be called and at least one root node should be
746 ///added with addSource() before using this function.
747 template<class NodeBoolMap>
748 Node start(const NodeBoolMap &nm)
750 while ( !_heap->empty() && !nm[_heap->top()] ) processNextNode();
751 if ( _heap->empty() ) return INVALID;
752 finalizeNodeData(_heap->top(),_heap->prio());
756 ///Runs the algorithm from the given source node.
758 ///This method runs the %Dijkstra algorithm from node \c s
759 ///in order to compute the shortest path to each node.
761 ///The algorithm computes
762 ///- the shortest path tree,
763 ///- the distance of each node from the root.
765 ///\note <tt>d.run(s)</tt> is just a shortcut of the following code.
777 ///Finds the shortest path between \c s and \c t.
779 ///This method runs the %Dijkstra algorithm from node \c s
780 ///in order to compute the shortest path to node \c t
781 ///(it stops searching when \c t is processed).
783 ///\return \c true if \c t is reachable form \c s.
785 ///\note Apart from the return value, <tt>d.run(s,t)</tt> is just a
786 ///shortcut of the following code.
792 bool run(Node s,Node t) {
796 return (*_heap_cross_ref)[t] == Heap::POST_HEAP;
801 ///\name Query Functions
802 ///The results of the %Dijkstra algorithm can be obtained using these
804 ///Either \ref run(Node) "run()" or \ref start() should be called
805 ///before using them.
809 ///The shortest path to a node.
811 ///Returns the shortest path to a node.
813 ///\warning \c t should be reached from the root(s).
815 ///\pre Either \ref run(Node) "run()" or \ref init()
816 ///must be called before using this function.
817 Path path(Node t) const { return Path(*G, *_pred, t); }
819 ///The distance of a node from the root(s).
821 ///Returns the distance of a node from the root(s).
823 ///\warning If node \c v is not reached from the root(s), then
824 ///the return value of this function is undefined.
826 ///\pre Either \ref run(Node) "run()" or \ref init()
827 ///must be called before using this function.
828 Value dist(Node v) const { return (*_dist)[v]; }
830 ///Returns the 'previous arc' of the shortest path tree for a node.
832 ///This function returns the 'previous arc' of the shortest path
833 ///tree for the node \c v, i.e. it returns the last arc of a
834 ///shortest path from a root to \c v. It is \c INVALID if \c v
835 ///is not reached from the root(s) or if \c v is a root.
837 ///The shortest path tree used here is equal to the shortest path
838 ///tree used in \ref predNode().
840 ///\pre Either \ref run(Node) "run()" or \ref init()
841 ///must be called before using this function.
842 Arc predArc(Node v) const { return (*_pred)[v]; }
844 ///Returns the 'previous node' of the shortest path tree for a node.
846 ///This function returns the 'previous node' of the shortest path
847 ///tree for the node \c v, i.e. it returns the last but one node
848 ///from a shortest path from a root to \c v. It is \c INVALID
849 ///if \c v is not reached from the root(s) or if \c v is a root.
851 ///The shortest path tree used here is equal to the shortest path
852 ///tree used in \ref predArc().
854 ///\pre Either \ref run(Node) "run()" or \ref init()
855 ///must be called before using this function.
856 Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
857 G->source((*_pred)[v]); }
859 ///\brief Returns a const reference to the node map that stores the
860 ///distances of the nodes.
862 ///Returns a const reference to the node map that stores the distances
863 ///of the nodes calculated by the algorithm.
865 ///\pre Either \ref run(Node) "run()" or \ref init()
866 ///must be called before using this function.
867 const DistMap &distMap() const { return *_dist;}
869 ///\brief Returns a const reference to the node map that stores the
872 ///Returns a const reference to the node map that stores the predecessor
873 ///arcs, which form the shortest path tree.
875 ///\pre Either \ref run(Node) "run()" or \ref init()
876 ///must be called before using this function.
877 const PredMap &predMap() const { return *_pred;}
879 ///Checks if a node is reached from the root(s).
881 ///Returns \c true if \c v is reached from the root(s).
883 ///\pre Either \ref run(Node) "run()" or \ref init()
884 ///must be called before using this function.
885 bool reached(Node v) const { return (*_heap_cross_ref)[v] !=
888 ///Checks if a node is processed.
890 ///Returns \c true if \c v is processed, i.e. the shortest
891 ///path to \c v has already found.
893 ///\pre Either \ref run(Node) "run()" or \ref init()
894 ///must be called before using this function.
895 bool processed(Node v) const { return (*_heap_cross_ref)[v] ==
898 ///The current distance of a node from the root(s).
900 ///Returns the current distance of a node from the root(s).
901 ///It may be decreased in the following processes.
903 ///\pre Either \ref run(Node) "run()" or \ref init()
904 ///must be called before using this function and
905 ///node \c v must be reached but not necessarily processed.
906 Value currentDist(Node v) const {
907 return processed(v) ? (*_dist)[v] : (*_heap)[v];
914 ///Default traits class of dijkstra() function.
916 ///Default traits class of dijkstra() function.
917 ///\tparam GR The type of the digraph.
918 ///\tparam LEN The type of the length map.
919 template<class GR, class LEN>
920 struct DijkstraWizardDefaultTraits
922 ///The type of the digraph the algorithm runs on.
924 ///The type of the map that stores the arc lengths.
926 ///The type of the map that stores the arc lengths.
927 ///It must meet the \ref concepts::ReadMap "ReadMap" concept.
928 typedef LEN LengthMap;
929 ///The type of the length of the arcs.
930 typedef typename LEN::Value Value;
932 /// Operation traits for Dijkstra algorithm.
934 /// This class defines the operations that are used in the algorithm.
935 /// \see DijkstraDefaultOperationTraits
936 typedef DijkstraDefaultOperationTraits<Value> OperationTraits;
938 /// The cross reference type used by the heap.
940 /// The cross reference type used by the heap.
941 /// Usually it is \c Digraph::NodeMap<int>.
942 typedef typename Digraph::template NodeMap<int> HeapCrossRef;
943 ///Instantiates a \ref HeapCrossRef.
945 ///This function instantiates a \ref HeapCrossRef.
946 /// \param g is the digraph, to which we would like to define the
948 static HeapCrossRef *createHeapCrossRef(const Digraph &g)
950 return new HeapCrossRef(g);
953 ///The heap type used by the Dijkstra algorithm.
955 ///The heap type used by the Dijkstra algorithm.
959 typedef BinHeap<Value, typename Digraph::template NodeMap<int>,
960 std::less<Value> > Heap;
962 ///Instantiates a \ref Heap.
964 ///This function instantiates a \ref Heap.
965 /// \param r is the HeapCrossRef which is used.
966 static Heap *createHeap(HeapCrossRef& r)
971 ///\brief The type of the map that stores the predecessor
972 ///arcs of the shortest paths.
974 ///The type of the map that stores the predecessor
975 ///arcs of the shortest paths.
976 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
977 typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
978 ///Instantiates a PredMap.
980 ///This function instantiates a PredMap.
981 ///\param g is the digraph, to which we would like to define the
983 static PredMap *createPredMap(const Digraph &g)
985 return new PredMap(g);
988 ///The type of the map that indicates which nodes are processed.
990 ///The type of the map that indicates which nodes are processed.
991 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
992 ///By default it is a NullMap.
993 typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
994 ///Instantiates a ProcessedMap.
996 ///This function instantiates a ProcessedMap.
997 ///\param g is the digraph, to which
998 ///we would like to define the ProcessedMap.
1000 static ProcessedMap *createProcessedMap(const Digraph &g)
1002 static ProcessedMap *createProcessedMap(const Digraph &)
1005 return new ProcessedMap();
1008 ///The type of the map that stores the distances of the nodes.
1010 ///The type of the map that stores the distances of the nodes.
1011 ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
1012 typedef typename Digraph::template NodeMap<typename LEN::Value> DistMap;
1013 ///Instantiates a DistMap.
1015 ///This function instantiates a DistMap.
1016 ///\param g is the digraph, to which we would like to define
1018 static DistMap *createDistMap(const Digraph &g)
1020 return new DistMap(g);
1023 ///The type of the shortest paths.
1025 ///The type of the shortest paths.
1026 ///It must meet the \ref concepts::Path "Path" concept.
1027 typedef lemon::Path<Digraph> Path;
1030 /// Default traits class used by DijkstraWizard
1032 /// To make it easier to use Dijkstra algorithm
1033 /// we have created a wizard class.
1034 /// This \ref DijkstraWizard class needs default traits,
1035 /// as well as the \ref Dijkstra class.
1036 /// The \ref DijkstraWizardBase is a class to be the default traits of the
1037 /// \ref DijkstraWizard class.
1038 template<typename GR, typename LEN>
1039 class DijkstraWizardBase : public DijkstraWizardDefaultTraits<GR,LEN>
1041 typedef DijkstraWizardDefaultTraits<GR,LEN> Base;
1043 //The type of the nodes in the digraph.
1044 typedef typename Base::Digraph::Node Node;
1046 //Pointer to the digraph the algorithm runs on.
1048 //Pointer to the length map.
1050 //Pointer to the map of processed nodes.
1052 //Pointer to the map of predecessors arcs.
1054 //Pointer to the map of distances.
1056 //Pointer to the shortest path to the target node.
1058 //Pointer to the distance of the target node.
1064 /// This constructor does not require parameters, therefore it initiates
1065 /// all of the attributes to \c 0.
1066 DijkstraWizardBase() : _g(0), _length(0), _processed(0), _pred(0),
1067 _dist(0), _path(0), _di(0) {}
1071 /// This constructor requires two parameters,
1072 /// others are initiated to \c 0.
1073 /// \param g The digraph the algorithm runs on.
1074 /// \param l The length map.
1075 DijkstraWizardBase(const GR &g,const LEN &l) :
1076 _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
1077 _length(reinterpret_cast<void*>(const_cast<LEN*>(&l))),
1078 _processed(0), _pred(0), _dist(0), _path(0), _di(0) {}
1082 /// Auxiliary class for the function-type interface of Dijkstra algorithm.
1084 /// This auxiliary class is created to implement the
1085 /// \ref dijkstra() "function-type interface" of \ref Dijkstra algorithm.
1086 /// It does not have own \ref run(Node) "run()" method, it uses the
1087 /// functions and features of the plain \ref Dijkstra.
1089 /// This class should only be used through the \ref dijkstra() function,
1090 /// which makes it easier to use the algorithm.
1092 class DijkstraWizard : public TR
1096 ///The type of the digraph the algorithm runs on.
1097 typedef typename TR::Digraph Digraph;
1099 typedef typename Digraph::Node Node;
1100 typedef typename Digraph::NodeIt NodeIt;
1101 typedef typename Digraph::Arc Arc;
1102 typedef typename Digraph::OutArcIt OutArcIt;
1104 ///The type of the map that stores the arc lengths.
1105 typedef typename TR::LengthMap LengthMap;
1106 ///The type of the length of the arcs.
1107 typedef typename LengthMap::Value Value;
1108 ///\brief The type of the map that stores the predecessor
1109 ///arcs of the shortest paths.
1110 typedef typename TR::PredMap PredMap;
1111 ///The type of the map that stores the distances of the nodes.
1112 typedef typename TR::DistMap DistMap;
1113 ///The type of the map that indicates which nodes are processed.
1114 typedef typename TR::ProcessedMap ProcessedMap;
1115 ///The type of the shortest paths
1116 typedef typename TR::Path Path;
1117 ///The heap type used by the dijkstra algorithm.
1118 typedef typename TR::Heap Heap;
1123 DijkstraWizard() : TR() {}
1125 /// Constructor that requires parameters.
1127 /// Constructor that requires parameters.
1128 /// These parameters will be the default values for the traits class.
1129 /// \param g The digraph the algorithm runs on.
1130 /// \param l The length map.
1131 DijkstraWizard(const Digraph &g, const LengthMap &l) :
1135 DijkstraWizard(const TR &b) : TR(b) {}
1137 ~DijkstraWizard() {}
1139 ///Runs Dijkstra algorithm from the given source node.
1141 ///This method runs %Dijkstra algorithm from the given source node
1142 ///in order to compute the shortest path to each node.
1145 Dijkstra<Digraph,LengthMap,TR>
1146 dijk(*reinterpret_cast<const Digraph*>(Base::_g),
1147 *reinterpret_cast<const LengthMap*>(Base::_length));
1149 dijk.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1151 dijk.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1152 if (Base::_processed)
1153 dijk.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1157 ///Finds the shortest path between \c s and \c t.
1159 ///This method runs the %Dijkstra algorithm from node \c s
1160 ///in order to compute the shortest path to node \c t
1161 ///(it stops searching when \c t is processed).
1163 ///\return \c true if \c t is reachable form \c s.
1164 bool run(Node s, Node t)
1166 Dijkstra<Digraph,LengthMap,TR>
1167 dijk(*reinterpret_cast<const Digraph*>(Base::_g),
1168 *reinterpret_cast<const LengthMap*>(Base::_length));
1170 dijk.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1172 dijk.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1173 if (Base::_processed)
1174 dijk.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1177 *reinterpret_cast<Path*>(Base::_path) = dijk.path(t);
1179 *reinterpret_cast<Value*>(Base::_di) = dijk.dist(t);
1180 return dijk.reached(t);
1184 struct SetPredMapBase : public Base {
1186 static PredMap *createPredMap(const Digraph &) { return 0; };
1187 SetPredMapBase(const TR &b) : TR(b) {}
1189 ///\brief \ref named-func-param "Named parameter"
1190 ///for setting PredMap object.
1192 ///\ref named-func-param "Named parameter"
1193 ///for setting PredMap object.
1195 DijkstraWizard<SetPredMapBase<T> > predMap(const T &t)
1197 Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1198 return DijkstraWizard<SetPredMapBase<T> >(*this);
1202 struct SetDistMapBase : public Base {
1204 static DistMap *createDistMap(const Digraph &) { return 0; };
1205 SetDistMapBase(const TR &b) : TR(b) {}
1207 ///\brief \ref named-func-param "Named parameter"
1208 ///for setting DistMap object.
1210 ///\ref named-func-param "Named parameter"
1211 ///for setting DistMap object.
1213 DijkstraWizard<SetDistMapBase<T> > distMap(const T &t)
1215 Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1216 return DijkstraWizard<SetDistMapBase<T> >(*this);
1220 struct SetProcessedMapBase : public Base {
1221 typedef T ProcessedMap;
1222 static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
1223 SetProcessedMapBase(const TR &b) : TR(b) {}
1225 ///\brief \ref named-func-param "Named parameter"
1226 ///for setting ProcessedMap object.
1228 /// \ref named-func-param "Named parameter"
1229 ///for setting ProcessedMap object.
1231 DijkstraWizard<SetProcessedMapBase<T> > processedMap(const T &t)
1233 Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1234 return DijkstraWizard<SetProcessedMapBase<T> >(*this);
1238 struct SetPathBase : public Base {
1240 SetPathBase(const TR &b) : TR(b) {}
1242 ///\brief \ref named-func-param "Named parameter"
1243 ///for getting the shortest path to the target node.
1245 ///\ref named-func-param "Named parameter"
1246 ///for getting the shortest path to the target node.
1248 DijkstraWizard<SetPathBase<T> > path(const T &t)
1250 Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t));
1251 return DijkstraWizard<SetPathBase<T> >(*this);
1254 ///\brief \ref named-func-param "Named parameter"
1255 ///for getting the distance of the target node.
1257 ///\ref named-func-param "Named parameter"
1258 ///for getting the distance of the target node.
1259 DijkstraWizard dist(const Value &d)
1261 Base::_di=reinterpret_cast<void*>(const_cast<Value*>(&d));
1267 ///Function-type interface for Dijkstra algorithm.
1269 /// \ingroup shortest_path
1270 ///Function-type interface for Dijkstra algorithm.
1272 ///This function also has several \ref named-func-param "named parameters",
1273 ///they are declared as the members of class \ref DijkstraWizard.
1274 ///The following examples show how to use these parameters.
1276 /// // Compute shortest path from node s to each node
1277 /// dijkstra(g,length).predMap(preds).distMap(dists).run(s);
1279 /// // Compute shortest path from s to t
1280 /// bool reached = dijkstra(g,length).path(p).dist(d).run(s,t);
1282 ///\warning Don't forget to put the \ref DijkstraWizard::run(Node) "run()"
1283 ///to the end of the parameter list.
1284 ///\sa DijkstraWizard
1286 template<typename GR, typename LEN>
1287 DijkstraWizard<DijkstraWizardBase<GR,LEN> >
1288 dijkstra(const GR &digraph, const LEN &length)
1290 return DijkstraWizard<DijkstraWizardBase<GR,LEN> >(digraph,length);
1293 } //END OF NAMESPACE LEMON