COIN-OR::LEMON - Graph Library

source: lemon-0.x/lemon/dijkstra.h @ 1734:2fb5ceac10e7

Last change on this file since 1734:2fb5ceac10e7 was 1734:2fb5ceac10e7, checked in by Alpar Juttner, 19 years ago
  • dijkstraZero() added. (Until we conclude how to handle the related problem.)
  • processed() query function added.
File size: 34.0 KB
RevLine 
[906]1/* -*- C++ -*-
[1435]2 * lemon/dijkstra.h - Part of LEMON, a generic C++ optimization library
[906]3 *
[1164]4 * Copyright (C) 2005 Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
[1359]5 * (Egervary Research Group on Combinatorial Optimization, EGRES).
[906]6 *
7 * Permission to use, modify and distribute this software is granted
8 * provided that this copyright notice appears in all copies. For
9 * precise terms see the accompanying LICENSE file.
10 *
11 * This software is provided "AS IS" with no warranty of any kind,
12 * express or implied, and with no claim as to its suitability for any
13 * purpose.
14 *
15 */
16
[921]17#ifndef LEMON_DIJKSTRA_H
18#define LEMON_DIJKSTRA_H
[255]19
[758]20///\ingroup flowalgs
[255]21///\file
22///\brief Dijkstra algorithm.
[1283]23///
24///\todo getPath() should be implemented! (also for BFS and DFS)
[1734]25///\todo dijkstraZero() solution should be revised.
[255]26
[953]27#include <lemon/list_graph.h>
[921]28#include <lemon/bin_heap.h>
29#include <lemon/invalid.h>
[1119]30#include <lemon/error.h>
31#include <lemon/maps.h>
[255]32
[921]33namespace lemon {
[385]34
[1734]35  template<class T> T dijkstraZero() {return 0;}
[1151]36 
[954]37  ///Default traits class of Dijkstra class.
38
39  ///Default traits class of Dijkstra class.
40  ///\param GR Graph type.
41  ///\param LM Type of length map.
[953]42  template<class GR, class LM>
43  struct DijkstraDefaultTraits
44  {
[954]45    ///The graph type the algorithm runs on.
[953]46    typedef GR Graph;
47    ///The type of the map that stores the edge lengths.
48
[1124]49    ///The type of the map that stores the edge lengths.
[967]50    ///It must meet the \ref concept::ReadMap "ReadMap" concept.
[953]51    typedef LM LengthMap;
[954]52    //The type of the length of the edges.
[987]53    typedef typename LM::Value Value;
[1721]54    /// The cross reference type used by heap.
55
56    /// The cross reference type used by heap.
57    /// Usually it is \c Graph::NodeMap<int>.
58    typedef typename Graph::template NodeMap<int> HeapCrossRef;
59    ///Instantiates a HeapCrossRef.
60
61    ///This function instantiates a \ref HeapCrossRef.
62    /// \param G is the graph, to which we would like to define the
63    /// HeapCrossRef.
64    /// \todo The graph alone may be insufficient for the initialization
65    static HeapCrossRef *createHeapCrossRef(const GR &G)
66    {
67      return new HeapCrossRef(G);
68    }
69   
[954]70    ///The heap type used by Dijkstra algorithm.
[967]71
72    ///The heap type used by Dijkstra algorithm.
73    ///
74    ///\sa BinHeap
75    ///\sa Dijkstra
[1709]76    typedef BinHeap<typename Graph::Node, typename LM::Value,
[953]77                    typename GR::template NodeMap<int>,
[987]78                    std::less<Value> > Heap;
[953]79
[1721]80    static Heap *createHeap(HeapCrossRef& R)
81    {
82      return new Heap(R);
83    }
84
[953]85    ///\brief The type of the map that stores the last
86    ///edges of the shortest paths.
87    ///
[1124]88    ///The type of the map that stores the last
89    ///edges of the shortest paths.
[967]90    ///It must meet the \ref concept::WriteMap "WriteMap" concept.
[953]91    ///
[954]92    typedef typename Graph::template NodeMap<typename GR::Edge> PredMap;
93    ///Instantiates a PredMap.
[953]94 
[1123]95    ///This function instantiates a \ref PredMap.
96    ///\param G is the graph, to which we would like to define the PredMap.
[1119]97    ///\todo The graph alone may be insufficient for the initialization
[954]98    static PredMap *createPredMap(const GR &G)
[953]99    {
100      return new PredMap(G);
101    }
[1119]102
[1218]103    ///The type of the map that stores whether a nodes is processed.
[1119]104 
[1218]105    ///The type of the map that stores whether a nodes is processed.
[1119]106    ///It must meet the \ref concept::WriteMap "WriteMap" concept.
107    ///By default it is a NullMap.
[1218]108    ///\todo If it is set to a real map,
109    ///Dijkstra::processed() should read this.
[1119]110    ///\todo named parameter to set this type, function to read and write.
[1218]111    typedef NullMap<typename Graph::Node,bool> ProcessedMap;
112    ///Instantiates a ProcessedMap.
[1119]113 
[1218]114    ///This function instantiates a \ref ProcessedMap.
[1536]115    ///\param g is the graph, to which
[1218]116    ///we would like to define the \ref ProcessedMap
[1536]117#ifdef DOXYGEN
118    static ProcessedMap *createProcessedMap(const GR &g)
119#else
[1366]120    static ProcessedMap *createProcessedMap(const GR &)
[1536]121#endif
[1119]122    {
[1218]123      return new ProcessedMap();
[1119]124    }
[953]125    ///The type of the map that stores the dists of the nodes.
126 
[1124]127    ///The type of the map that stores the dists of the nodes.
[967]128    ///It must meet the \ref concept::WriteMap "WriteMap" concept.
[953]129    ///
[987]130    typedef typename Graph::template NodeMap<typename LM::Value> DistMap;
[954]131    ///Instantiates a DistMap.
[953]132 
[1123]133    ///This function instantiates a \ref DistMap.
134    ///\param G is the graph, to which we would like to define the \ref DistMap
[954]135    static DistMap *createDistMap(const GR &G)
[953]136    {
137      return new DistMap(G);
138    }
139  };
140 
[255]141  ///%Dijkstra algorithm class.
[1125]142 
[1151]143  /// \ingroup flowalgs
[255]144  ///This class provides an efficient implementation of %Dijkstra algorithm.
145  ///The edge lengths are passed to the algorithm using a
[959]146  ///\ref concept::ReadMap "ReadMap",
[255]147  ///so it is easy to change it to any kind of length.
148  ///
[880]149  ///The type of the length is determined by the
[987]150  ///\ref concept::ReadMap::Value "Value" of the length map.
[255]151  ///
152  ///It is also possible to change the underlying priority heap.
153  ///
[1218]154  ///\param GR The graph type the algorithm runs on. The default value
155  ///is \ref ListGraph. The value of GR is not used directly by
156  ///Dijkstra, it is only passed to \ref DijkstraDefaultTraits.
157  ///\param LM This read-only EdgeMap determines the lengths of the
158  ///edges. It is read once for each edge, so the map may involve in
159  ///relatively time consuming process to compute the edge length if
160  ///it is necessary. The default map type is \ref
161  ///concept::StaticGraph::EdgeMap "Graph::EdgeMap<int>".  The value
162  ///of LM is not used directly by Dijkstra, it is only passed to \ref
163  ///DijkstraDefaultTraits.  \param TR Traits class to set
164  ///various data types used by the algorithm.  The default traits
165  ///class is \ref DijkstraDefaultTraits
166  ///"DijkstraDefaultTraits<GR,LM>".  See \ref
167  ///DijkstraDefaultTraits for the documentation of a Dijkstra traits
168  ///class.
[456]169  ///
[689]170  ///\author Jacint Szabo and Alpar Juttner
[1128]171  ///\todo A compare object would be nice.
[584]172
[255]173#ifdef DOXYGEN
[584]174  template <typename GR,
175            typename LM,
[953]176            typename TR>
[255]177#else
[953]178  template <typename GR=ListGraph,
[584]179            typename LM=typename GR::template EdgeMap<int>,
[953]180            typename TR=DijkstraDefaultTraits<GR,LM> >
[255]181#endif
[1116]182  class Dijkstra {
[255]183  public:
[1125]184    /**
185     * \brief \ref Exception for uninitialized parameters.
186     *
187     * This error represents problems in the initialization
188     * of the parameters of the algorithms.
189     */
190    class UninitializedParameter : public lemon::UninitializedParameter {
191    public:
192      virtual const char* exceptionName() const {
[1218]193        return "lemon::Dijkstra::UninitializedParameter";
[1125]194      }
195    };
[1119]196
[953]197    typedef TR Traits;
[584]198    ///The type of the underlying graph.
[954]199    typedef typename TR::Graph Graph;
[911]200    ///\e
[255]201    typedef typename Graph::Node Node;
[911]202    ///\e
[255]203    typedef typename Graph::NodeIt NodeIt;
[911]204    ///\e
[255]205    typedef typename Graph::Edge Edge;
[911]206    ///\e
[255]207    typedef typename Graph::OutEdgeIt OutEdgeIt;
208   
[584]209    ///The type of the length of the edges.
[987]210    typedef typename TR::LengthMap::Value Value;
[693]211    ///The type of the map that stores the edge lengths.
[954]212    typedef typename TR::LengthMap LengthMap;
[693]213    ///\brief The type of the map that stores the last
[584]214    ///edges of the shortest paths.
[953]215    typedef typename TR::PredMap PredMap;
[1218]216    ///The type of the map indicating if a node is processed.
217    typedef typename TR::ProcessedMap ProcessedMap;
[693]218    ///The type of the map that stores the dists of the nodes.
[953]219    typedef typename TR::DistMap DistMap;
[1721]220    ///The cross reference type used for the current heap.
221    typedef typename TR::HeapCrossRef HeapCrossRef;
[953]222    ///The heap type used by the dijkstra algorithm.
223    typedef typename TR::Heap Heap;
[255]224  private:
[802]225    /// Pointer to the underlying graph.
[688]226    const Graph *G;
[802]227    /// Pointer to the length map
[954]228    const LengthMap *length;
[802]229    ///Pointer to the map of predecessors edges.
[1119]230    PredMap *_pred;
231    ///Indicates if \ref _pred is locally allocated (\c true) or not.
232    bool local_pred;
[802]233    ///Pointer to the map of distances.
[1130]234    DistMap *_dist;
235    ///Indicates if \ref _dist is locally allocated (\c true) or not.
236    bool local_dist;
[1218]237    ///Pointer to the map of processed status of the nodes.
238    ProcessedMap *_processed;
239    ///Indicates if \ref _processed is locally allocated (\c true) or not.
240    bool local_processed;
[1721]241    ///Pointer to the heap cross references.
242    HeapCrossRef *_heap_cross_ref;
243    ///Indicates if \ref _heap_cross_ref is locally allocated (\c true) or not.
244    bool local_heap_cross_ref;
245    ///Pointer to the heap.
246    Heap *_heap;
247    ///Indicates if \ref _heap is locally allocated (\c true) or not.
248    bool local_heap;
[688]249
[1128]250    ///Creates the maps if necessary.
[688]251   
[694]252    ///\todo Error if \c G or are \c NULL. What about \c length?
[688]253    ///\todo Better memory allocation (instead of new).
[1128]254    void create_maps()
[688]255    {
[1119]256      if(!_pred) {
257        local_pred = true;
258        _pred = Traits::createPredMap(*G);
[688]259      }
[1130]260      if(!_dist) {
261        local_dist = true;
262        _dist = Traits::createDistMap(*G);
[688]263      }
[1218]264      if(!_processed) {
265        local_processed = true;
266        _processed = Traits::createProcessedMap(*G);
[1119]267      }
[1721]268      if (!_heap_cross_ref) {
269        local_heap_cross_ref = true;
270        _heap_cross_ref = Traits::createHeapCrossRef(*G);
271      }
272      if (!_heap) {
273        local_heap = true;
274        _heap = Traits::createHeap(*_heap_cross_ref);
275      }
[688]276    }
[255]277   
278  public :
[1710]279
280    typedef Dijkstra Create;
[1116]281 
[1128]282    ///\name Named template parameters
283
284    ///@{
285
[953]286    template <class T>
[1116]287    struct DefPredMapTraits : public Traits {
[953]288      typedef T PredMap;
289      static PredMap *createPredMap(const Graph &G)
290      {
[1126]291        throw UninitializedParameter();
[953]292      }
293    };
[954]294    ///\ref named-templ-param "Named parameter" for setting PredMap type
295
296    ///\ref named-templ-param "Named parameter" for setting PredMap type
[1043]297    ///
[953]298    template <class T>
[1709]299    struct DefPredMap
300      : public Dijkstra< Graph, LengthMap, DefPredMapTraits<T> > {
301      typedef Dijkstra< Graph,  LengthMap, DefPredMapTraits<T> > Create;
302    };
[953]303   
304    template <class T>
[1116]305    struct DefDistMapTraits : public Traits {
[953]306      typedef T DistMap;
307      static DistMap *createDistMap(const Graph &G)
308      {
[1126]309        throw UninitializedParameter();
[953]310      }
311    };
[954]312    ///\ref named-templ-param "Named parameter" for setting DistMap type
313
314    ///\ref named-templ-param "Named parameter" for setting DistMap type
[1043]315    ///
[953]316    template <class T>
[1709]317    struct DefDistMap
318      : public Dijkstra< Graph, LengthMap, DefDistMapTraits<T> > {
319      typedef Dijkstra< Graph, LengthMap, DefDistMapTraits<T> > Create;
320    };
[953]321   
[1128]322    template <class T>
[1218]323    struct DefProcessedMapTraits : public Traits {
324      typedef T ProcessedMap;
325      static ProcessedMap *createProcessedMap(const Graph &G)
[1128]326      {
327        throw UninitializedParameter();
328      }
329    };
[1218]330    ///\ref named-templ-param "Named parameter" for setting ProcessedMap type
[1128]331
[1218]332    ///\ref named-templ-param "Named parameter" for setting ProcessedMap type
[1128]333    ///
334    template <class T>
[1709]335    struct DefProcessedMap
336      : public Dijkstra< Graph, LengthMap, DefProcessedMapTraits<T> > {
337      typedef Dijkstra< Graph,  LengthMap, DefProcessedMapTraits<T> > Create;
338    };
[1128]339   
[1218]340    struct DefGraphProcessedMapTraits : public Traits {
341      typedef typename Graph::template NodeMap<bool> ProcessedMap;
342      static ProcessedMap *createProcessedMap(const Graph &G)
[1128]343      {
[1218]344        return new ProcessedMap(G);
[1128]345      }
346    };
347    ///\brief \ref named-templ-param "Named parameter"
[1218]348    ///for setting the ProcessedMap type to be Graph::NodeMap<bool>.
[1128]349    ///
350    ///\ref named-templ-param "Named parameter"
[1218]351    ///for setting the ProcessedMap type to be Graph::NodeMap<bool>.
[1128]352    ///If you don't set it explicitely, it will be automatically allocated.
353    template <class T>
[1709]354    struct DefProcessedMapToBeDefaultMap
355      : public Dijkstra< Graph, LengthMap, DefGraphProcessedMapTraits> {
356      typedef Dijkstra< Graph, LengthMap, DefGraphProcessedMapTraits> Create;
357    };
[1721]358
359    template <class H, class CR>
360    struct DefHeapTraits : public Traits {
361      typedef CR HeapCrossRef;
362      typedef H Heap;
363      static HeapCrossRef *createHeapCrossRef(const Graph &G) {
364        return new HeapCrossRef(G);
365      }
366      static Heap *createHeap(HeapCrossRef &R)
367      {
368        return new Heap(R);
369      }
370    };
371    ///\ref named-templ-param "Named parameter" for setting heap and cross
372    ///reference type
373
374    ///\ref named-templ-param "Named parameter" for setting heap and cross
375    ///reference type
376    ///
377    template <class H, class CR = typename Graph::template NodeMap<int> >
378    struct DefHeap
379      : public Dijkstra< Graph, LengthMap, DefHeapTraits<H, CR> > {
380      typedef Dijkstra< Graph,  LengthMap, DefHeapTraits<H, CR> > Create;
381    };
[1128]382   
383    ///@}
384
385
[1710]386  protected:
387
388    Dijkstra() {}
389
[1128]390  public:     
391   
[802]392    ///Constructor.
[255]393   
[802]394    ///\param _G the graph the algorithm will run on.
395    ///\param _length the length map used by the algorithm.
[954]396    Dijkstra(const Graph& _G, const LengthMap& _length) :
[688]397      G(&_G), length(&_length),
[1119]398      _pred(NULL), local_pred(false),
[1130]399      _dist(NULL), local_dist(false),
[1218]400      _processed(NULL), local_processed(false),
[1721]401      _heap_cross_ref(NULL), local_heap_cross_ref(false),
402      _heap(NULL), local_heap(false)
[688]403    { }
404   
[802]405    ///Destructor.
[688]406    ~Dijkstra()
407    {
[1119]408      if(local_pred) delete _pred;
[1130]409      if(local_dist) delete _dist;
[1218]410      if(local_processed) delete _processed;
[1721]411      if(local_heap_cross_ref) delete _heap_cross_ref;
412      if(local_heap) delete _heap;
[688]413    }
414
415    ///Sets the length map.
416
417    ///Sets the length map.
418    ///\return <tt> (*this) </tt>
[1116]419    Dijkstra &lengthMap(const LengthMap &m)
[688]420    {
421      length = &m;
422      return *this;
423    }
424
425    ///Sets the map storing the predecessor edges.
426
427    ///Sets the map storing the predecessor edges.
428    ///If you don't use this function before calling \ref run(),
429    ///it will allocate one. The destuctor deallocates this
430    ///automatically allocated map, of course.
431    ///\return <tt> (*this) </tt>
[1116]432    Dijkstra &predMap(PredMap &m)
[688]433    {
[1119]434      if(local_pred) {
435        delete _pred;
436        local_pred=false;
[688]437      }
[1119]438      _pred = &m;
[688]439      return *this;
440    }
441
442    ///Sets the map storing the distances calculated by the algorithm.
443
444    ///Sets the map storing the distances calculated by the algorithm.
445    ///If you don't use this function before calling \ref run(),
446    ///it will allocate one. The destuctor deallocates this
447    ///automatically allocated map, of course.
448    ///\return <tt> (*this) </tt>
[1116]449    Dijkstra &distMap(DistMap &m)
[688]450    {
[1130]451      if(local_dist) {
452        delete _dist;
453        local_dist=false;
[688]454      }
[1130]455      _dist = &m;
[688]456      return *this;
457    }
[694]458
[1130]459  private:
460    void finalizeNodeData(Node v,Value dst)
461    {
[1218]462      _processed->set(v,true);
[1130]463      _dist->set(v, dst);
464    }
465
466  public:
[1218]467    ///\name Execution control
[1128]468    ///The simplest way to execute the algorithm is to use
[1156]469    ///one of the member functions called \c run(...).
[1128]470    ///\n
[1218]471    ///If you need more control on the execution,
[1128]472    ///first you must call \ref init(), then you can add several source nodes
[1218]473    ///with \ref addSource().
474    ///Finally \ref start() will perform the actual path
[1128]475    ///computation.
476
477    ///@{
478
479    ///Initializes the internal data structures.
480
481    ///Initializes the internal data structures.
482    ///
483    void init()
484    {
485      create_maps();
[1721]486      _heap->clear();
[774]487      for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
[1119]488        _pred->set(u,INVALID);
[1218]489        _processed->set(u,false);
[1721]490        _heap_cross_ref->set(u,Heap::PRE_HEAP);
[694]491      }
[1128]492    }
493   
494    ///Adds a new source node.
495
[1155]496    ///Adds a new source node to the priority heap.
[1128]497    ///
498    ///The optional second parameter is the initial distance of the node.
499    ///
[1155]500    ///It checks if the node has already been added to the heap and
501    ///It is pushed to the heap only if either it was not in the heap
502    ///or the shortest path found till then is longer then \c dst.
[1734]503    void addSource(Node s,Value dst=dijkstraZero<Value>())
[1128]504    {
[1721]505      if(_heap->state(s) != Heap::IN_HEAP) {
506        _heap->push(s,dst);
507      } else if((*_heap)[s]<dst) {
508        _heap->push(s,dst);
[1155]509        _pred->set(s,INVALID);
510      }
[1128]511    }
512   
[1155]513    ///Processes the next node in the priority heap
514
515    ///Processes the next node in the priority heap.
516    ///
[1516]517    ///\return The processed node.
518    ///
[1155]519    ///\warning The priority heap must not be empty!
[1516]520    Node processNextNode()
[1128]521    {
[1721]522      Node v=_heap->top();
523      Value oldvalue=_heap->prio();
524      _heap->pop();
[1130]525      finalizeNodeData(v,oldvalue);
[694]526     
[1128]527      for(OutEdgeIt e(*G,v); e!=INVALID; ++e) {
528        Node w=G->target(e);
[1721]529        switch(_heap->state(w)) {
[1128]530        case Heap::PRE_HEAP:
[1721]531          _heap->push(w,oldvalue+(*length)[e]);
[1128]532          _pred->set(w,e);
533          break;
534        case Heap::IN_HEAP:
[1721]535          if ( oldvalue+(*length)[e] < (*_heap)[w] ) {
536            _heap->decrease(w, oldvalue+(*length)[e]);
[1119]537            _pred->set(w,e);
[694]538          }
[1128]539          break;
540        case Heap::POST_HEAP:
541          break;
[694]542        }
543      }
[1516]544      return v;
[694]545    }
[1128]546
[1665]547    ///Next node to be processed.
548   
549    ///Next node to be processed.
550    ///
551    ///\return The next node to be processed or INVALID if the priority heap
552    /// is empty.
[1694]553    Node nextNode()
[1665]554    {
[1721]555      return _heap->empty()?_heap->top():INVALID;
[1665]556    }
557 
[1218]558    ///\brief Returns \c false if there are nodes
559    ///to be processed in the priority heap
[1155]560    ///
[1218]561    ///Returns \c false if there are nodes
562    ///to be processed in the priority heap
[1721]563    bool emptyQueue() { return _heap->empty(); }
[1155]564    ///Returns the number of the nodes to be processed in the priority heap
565
566    ///Returns the number of the nodes to be processed in the priority heap
567    ///
[1721]568    int queueSize() { return _heap->size(); }
[1155]569   
[1130]570    ///Executes the algorithm.
[1128]571
[1130]572    ///Executes the algorithm.
[1128]573    ///
[1130]574    ///\pre init() must be called and at least one node should be added
575    ///with addSource() before using this function.
[1128]576    ///
577    ///This method runs the %Dijkstra algorithm from the root node(s)
578    ///in order to
579    ///compute the
580    ///shortest path to each node. The algorithm computes
581    ///- The shortest path tree.
582    ///- The distance of each node from the root(s).
583    ///
584    void start()
585    {
[1721]586      while ( !_heap->empty() ) processNextNode();
[1128]587    }
[255]588   
[1130]589    ///Executes the algorithm until \c dest is reached.
[1128]590
[1130]591    ///Executes the algorithm until \c dest is reached.
[1128]592    ///
[1130]593    ///\pre init() must be called and at least one node should be added
594    ///with addSource() before using this function.
[1128]595    ///
596    ///This method runs the %Dijkstra algorithm from the root node(s)
597    ///in order to
598    ///compute the
599    ///shortest path to \c dest. The algorithm computes
600    ///- The shortest path to \c  dest.
601    ///- The distance of \c dest from the root(s).
602    ///
603    void start(Node dest)
604    {
[1721]605      while ( !_heap->empty() && _heap->top()!=dest ) processNextNode();
606      if ( !_heap->empty() ) finalizeNodeData(_heap->top(),_heap->prio());
[1130]607    }
608   
609    ///Executes the algorithm until a condition is met.
610
611    ///Executes the algorithm until a condition is met.
612    ///
613    ///\pre init() must be called and at least one node should be added
614    ///with addSource() before using this function.
615    ///
616    ///\param nm must be a bool (or convertible) node map. The algorithm
617    ///will stop when it reaches a node \c v with <tt>nm[v]==true</tt>.
[1345]618    template<class NodeBoolMap>
619    void start(const NodeBoolMap &nm)
[1130]620    {
[1721]621      while ( !_heap->empty() && !nm[_heap->top()] ) processNextNode();
622      if ( !_heap->empty() ) finalizeNodeData(_heap->top(),_heap->prio());
[1128]623    }
624   
625    ///Runs %Dijkstra algorithm from node \c s.
626   
627    ///This method runs the %Dijkstra algorithm from a root node \c s
628    ///in order to
629    ///compute the
630    ///shortest path to each node. The algorithm computes
631    ///- The shortest path tree.
632    ///- The distance of each node from the root.
633    ///
634    ///\note d.run(s) is just a shortcut of the following code.
635    ///\code
636    ///  d.init();
637    ///  d.addSource(s);
638    ///  d.start();
639    ///\endcode
640    void run(Node s) {
641      init();
642      addSource(s);
643      start();
644    }
645   
[1130]646    ///Finds the shortest path between \c s and \c t.
647   
648    ///Finds the shortest path between \c s and \c t.
649    ///
650    ///\return The length of the shortest s---t path if there exists one,
651    ///0 otherwise.
652    ///\note Apart from the return value, d.run(s) is
653    ///just a shortcut of the following code.
654    ///\code
655    ///  d.init();
656    ///  d.addSource(s);
657    ///  d.start(t);
658    ///\endcode
659    Value run(Node s,Node t) {
660      init();
661      addSource(s);
662      start(t);
[1734]663      return (*_pred)[t]==INVALID?dijkstraZero<Value>():(*_dist)[t];
[1130]664    }
665   
[1128]666    ///@}
667
668    ///\name Query Functions
669    ///The result of the %Dijkstra algorithm can be obtained using these
670    ///functions.\n
671    ///Before the use of these functions,
672    ///either run() or start() must be called.
673   
674    ///@{
675
[1283]676    ///Copies the shortest path to \c t into \c p
677   
678    ///This function copies the shortest path to \c t into \c p.
[1536]679    ///If it \c t is a source itself or unreachable, then it does not
[1283]680    ///alter \c p.
681    ///\todo Is it the right way to handle unreachable nodes?
682    ///\return Returns \c true if a path to \c t was actually copied to \c p,
683    ///\c false otherwise.
684    ///\sa DirPath
685    template<class P>
686    bool getPath(P &p,Node t)
687    {
688      if(reached(t)) {
689        p.clear();
690        typename P::Builder b(p);
691        for(b.setStartNode(t);pred(t)!=INVALID;t=predNode(t))
692          b.pushFront(pred(t));
693        b.commit();
694        return true;
695      }
696      return false;
697    }
698         
[385]699    ///The distance of a node from the root.
[255]700
[385]701    ///Returns the distance of a node from the root.
[255]702    ///\pre \ref run() must be called before using this function.
[385]703    ///\warning If node \c v in unreachable from the root the return value
[255]704    ///of this funcion is undefined.
[1130]705    Value dist(Node v) const { return (*_dist)[v]; }
[373]706
[584]707    ///Returns the 'previous edge' of the shortest path tree.
[255]708
[584]709    ///For a node \c v it returns the 'previous edge' of the shortest path tree,
[785]710    ///i.e. it returns the last edge of a shortest path from the root to \c
[688]711    ///v. It is \ref INVALID
712    ///if \c v is unreachable from the root or if \c v=s. The
[385]713    ///shortest path tree used here is equal to the shortest path tree used in
[1631]714    ///\ref predNode().  \pre \ref run() must be called before using
[385]715    ///this function.
[780]716    ///\todo predEdge could be a better name.
[1119]717    Edge pred(Node v) const { return (*_pred)[v]; }
[373]718
[584]719    ///Returns the 'previous node' of the shortest path tree.
[255]720
[584]721    ///For a node \c v it returns the 'previous node' of the shortest path tree,
[385]722    ///i.e. it returns the last but one node from a shortest path from the
723    ///root to \c /v. It is INVALID if \c v is unreachable from the root or if
724    ///\c v=s. The shortest path tree used here is equal to the shortest path
[1631]725    ///tree used in \ref pred().  \pre \ref run() must be called before
[385]726    ///using this function.
[1130]727    Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
728                                  G->source((*_pred)[v]); }
[255]729   
730    ///Returns a reference to the NodeMap of distances.
731
[385]732    ///Returns a reference to the NodeMap of distances. \pre \ref run() must
733    ///be called before using this function.
[1130]734    const DistMap &distMap() const { return *_dist;}
[385]735 
[255]736    ///Returns a reference to the shortest path tree map.
737
738    ///Returns a reference to the NodeMap of the edges of the
739    ///shortest path tree.
740    ///\pre \ref run() must be called before using this function.
[1119]741    const PredMap &predMap() const { return *_pred;}
[385]742 
743    ///Checks if a node is reachable from the root.
[255]744
[385]745    ///Returns \c true if \c v is reachable from the root.
[1218]746    ///\warning The source nodes are inditated as unreached.
[255]747    ///\pre \ref run() must be called before using this function.
[385]748    ///
[1721]749    bool reached(Node v) { return (*_heap_cross_ref)[v] != Heap::PRE_HEAP; }
[1734]750
751    ///Checks if a node is processed.
752
753    ///Returns \c true if \c v is processed, i.e. the shortest
754    ///path to \c v has already found.
755    ///\pre \ref run() must be called before using this function.
756    ///
757    bool processed(Node v) { return (*_heap_cross_ref)[v] == Heap::POST_HEAP; }
[255]758   
[1128]759    ///@}
[255]760  };
[953]761
[1218]762
763
764
765 
766  ///Default traits class of Dijkstra function.
767
768  ///Default traits class of Dijkstra function.
769  ///\param GR Graph type.
770  ///\param LM Type of length map.
771  template<class GR, class LM>
772  struct DijkstraWizardDefaultTraits
773  {
774    ///The graph type the algorithm runs on.
775    typedef GR Graph;
776    ///The type of the map that stores the edge lengths.
777
778    ///The type of the map that stores the edge lengths.
779    ///It must meet the \ref concept::ReadMap "ReadMap" concept.
780    typedef LM LengthMap;
781    //The type of the length of the edges.
782    typedef typename LM::Value Value;
783    ///The heap type used by Dijkstra algorithm.
784
[1721]785    /// The cross reference type used by heap.
786
787    /// The cross reference type used by heap.
788    /// Usually it is \c Graph::NodeMap<int>.
789    typedef typename Graph::template NodeMap<int> HeapCrossRef;
790    ///Instantiates a HeapCrossRef.
791
792    ///This function instantiates a \ref HeapCrossRef.
793    /// \param G is the graph, to which we would like to define the
794    /// HeapCrossRef.
795    /// \todo The graph alone may be insufficient for the initialization
796    static HeapCrossRef *createHeapCrossRef(const GR &G)
797    {
798      return new HeapCrossRef(G);
799    }
800   
801    ///The heap type used by Dijkstra algorithm.
802
[1218]803    ///The heap type used by Dijkstra algorithm.
804    ///
805    ///\sa BinHeap
806    ///\sa Dijkstra
[1721]807    typedef BinHeap<typename Graph::Node, typename LM::Value,
[1218]808                    typename GR::template NodeMap<int>,
809                    std::less<Value> > Heap;
810
[1721]811    static Heap *createHeap(HeapCrossRef& R)
812    {
813      return new Heap(R);
814    }
815
[1218]816    ///\brief The type of the map that stores the last
817    ///edges of the shortest paths.
818    ///
819    ///The type of the map that stores the last
820    ///edges of the shortest paths.
821    ///It must meet the \ref concept::WriteMap "WriteMap" concept.
822    ///
823    typedef NullMap <typename GR::Node,typename GR::Edge> PredMap;
824    ///Instantiates a PredMap.
825 
826    ///This function instantiates a \ref PredMap.
[1536]827    ///\param g is the graph, to which we would like to define the PredMap.
[1218]828    ///\todo The graph alone may be insufficient for the initialization
[1536]829#ifdef DOXYGEN
830    static PredMap *createPredMap(const GR &g)
831#else
[1367]832    static PredMap *createPredMap(const GR &)
[1536]833#endif
[1218]834    {
835      return new PredMap();
836    }
837    ///The type of the map that stores whether a nodes is processed.
838 
839    ///The type of the map that stores whether a nodes is processed.
840    ///It must meet the \ref concept::WriteMap "WriteMap" concept.
841    ///By default it is a NullMap.
842    ///\todo If it is set to a real map,
843    ///Dijkstra::processed() should read this.
844    ///\todo named parameter to set this type, function to read and write.
845    typedef NullMap<typename Graph::Node,bool> ProcessedMap;
846    ///Instantiates a ProcessedMap.
847 
848    ///This function instantiates a \ref ProcessedMap.
[1536]849    ///\param g is the graph, to which
[1218]850    ///we would like to define the \ref ProcessedMap
[1536]851#ifdef DOXYGEN
852    static ProcessedMap *createProcessedMap(const GR &g)
853#else
[1367]854    static ProcessedMap *createProcessedMap(const GR &)
[1536]855#endif
[1218]856    {
857      return new ProcessedMap();
858    }
859    ///The type of the map that stores the dists of the nodes.
860 
861    ///The type of the map that stores the dists of the nodes.
862    ///It must meet the \ref concept::WriteMap "WriteMap" concept.
863    ///
864    typedef NullMap<typename Graph::Node,typename LM::Value> DistMap;
865    ///Instantiates a DistMap.
866 
867    ///This function instantiates a \ref DistMap.
[1536]868    ///\param g is the graph, to which we would like to define the \ref DistMap
869#ifdef DOXYGEN
870    static DistMap *createDistMap(const GR &g)
871#else
[1367]872    static DistMap *createDistMap(const GR &)
[1536]873#endif
[1218]874    {
875      return new DistMap();
876    }
877  };
878 
[1123]879  /// Default traits used by \ref DijkstraWizard
880
[1151]881  /// To make it easier to use Dijkstra algorithm
882  ///we have created a wizard class.
883  /// This \ref DijkstraWizard class needs default traits,
884  ///as well as the \ref Dijkstra class.
[1123]885  /// The \ref DijkstraWizardBase is a class to be the default traits of the
886  /// \ref DijkstraWizard class.
[1220]887  /// \todo More named parameters are required...
[1116]888  template<class GR,class LM>
[1218]889  class DijkstraWizardBase : public DijkstraWizardDefaultTraits<GR,LM>
[1116]890  {
891
[1218]892    typedef DijkstraWizardDefaultTraits<GR,LM> Base;
[1116]893  protected:
[1201]894    /// Type of the nodes in the graph.
895    typedef typename Base::Graph::Node Node;
896
[1116]897    /// Pointer to the underlying graph.
898    void *_g;
899    /// Pointer to the length map
900    void *_length;
901    ///Pointer to the map of predecessors edges.
902    void *_pred;
903    ///Pointer to the map of distances.
904    void *_dist;
905    ///Pointer to the source node.
[1201]906    Node _source;
[1116]907
908    public:
[1123]909    /// Constructor.
910   
911    /// This constructor does not require parameters, therefore it initiates
912    /// all of the attributes to default values (0, INVALID).
[1218]913    DijkstraWizardBase() : _g(0), _length(0), _pred(0),
914                           _dist(0), _source(INVALID) {}
[1116]915
[1123]916    /// Constructor.
917   
[1156]918    /// This constructor requires some parameters,
919    /// listed in the parameters list.
[1123]920    /// Others are initiated to 0.
921    /// \param g is the initial value of  \ref _g
922    /// \param l is the initial value of  \ref _length
923    /// \param s is the initial value of  \ref _source
[1116]924    DijkstraWizardBase(const GR &g,const LM &l, Node s=INVALID) :
[1218]925      _g((void *)&g), _length((void *)&l), _pred(0),
926      _dist(0), _source(s) {}
[1116]927
928  };
929 
[1229]930  /// A class to make the usage of Dijkstra algorithm easier
[953]931
[1123]932  /// This class is created to make it easier to use Dijkstra algorithm.
933  /// It uses the functions and features of the plain \ref Dijkstra,
[1151]934  /// but it is much simpler to use it.
[953]935  ///
[1123]936  /// Simplicity means that the way to change the types defined
937  /// in the traits class is based on functions that returns the new class
[1151]938  /// and not on templatable built-in classes.
939  /// When using the plain \ref Dijkstra
940  /// the new class with the modified type comes from
941  /// the original class by using the ::
942  /// operator. In the case of \ref DijkstraWizard only
943  /// a function have to be called and it will
[1123]944  /// return the needed class.
945  ///
946  /// It does not have own \ref run method. When its \ref run method is called
[1721]947  /// it initiates a plain \ref Dijkstra class, and calls the \ref
948  /// Dijkstra::run method of it.
[953]949  template<class TR>
[1116]950  class DijkstraWizard : public TR
[953]951  {
[1116]952    typedef TR Base;
[953]953
[1123]954    ///The type of the underlying graph.
[953]955    typedef typename TR::Graph Graph;
[1119]956    //\e
[953]957    typedef typename Graph::Node Node;
[1119]958    //\e
[953]959    typedef typename Graph::NodeIt NodeIt;
[1119]960    //\e
[953]961    typedef typename Graph::Edge Edge;
[1119]962    //\e
[953]963    typedef typename Graph::OutEdgeIt OutEdgeIt;
964   
[1123]965    ///The type of the map that stores the edge lengths.
[953]966    typedef typename TR::LengthMap LengthMap;
[1123]967    ///The type of the length of the edges.
[987]968    typedef typename LengthMap::Value Value;
[1123]969    ///\brief The type of the map that stores the last
970    ///edges of the shortest paths.
[953]971    typedef typename TR::PredMap PredMap;
[1123]972    ///The type of the map that stores the dists of the nodes.
[953]973    typedef typename TR::DistMap DistMap;
[1123]974    ///The heap type used by the dijkstra algorithm.
[953]975    typedef typename TR::Heap Heap;
[1116]976public:
[1123]977    /// Constructor.
[1116]978    DijkstraWizard() : TR() {}
[953]979
[1123]980    /// Constructor that requires parameters.
[1124]981
982    /// Constructor that requires parameters.
[1123]983    /// These parameters will be the default values for the traits class.
[1116]984    DijkstraWizard(const Graph &g,const LengthMap &l, Node s=INVALID) :
985      TR(g,l,s) {}
[953]986
[1123]987    ///Copy constructor
[1116]988    DijkstraWizard(const TR &b) : TR(b) {}
[953]989
[1116]990    ~DijkstraWizard() {}
991
[1123]992    ///Runs Dijkstra algorithm from a given node.
993   
994    ///Runs Dijkstra algorithm from a given node.
995    ///The node can be given by the \ref source function.
[1116]996    void run()
[953]997    {
[1201]998      if(Base::_source==INVALID) throw UninitializedParameter();
[1193]999      Dijkstra<Graph,LengthMap,TR>
[1345]1000        dij(*(Graph*)Base::_g,*(LengthMap*)Base::_length);
1001      if(Base::_pred) dij.predMap(*(PredMap*)Base::_pred);
1002      if(Base::_dist) dij.distMap(*(DistMap*)Base::_dist);
1003      dij.run(Base::_source);
[1116]1004    }
1005
[1124]1006    ///Runs Dijkstra algorithm from the given node.
[1123]1007
[1124]1008    ///Runs Dijkstra algorithm from the given node.
[1123]1009    ///\param s is the given source.
[1116]1010    void run(Node s)
1011    {
[1201]1012      Base::_source=s;
[1116]1013      run();
[953]1014    }
1015
1016    template<class T>
[1116]1017    struct DefPredMapBase : public Base {
1018      typedef T PredMap;
[1367]1019      static PredMap *createPredMap(const Graph &) { return 0; };
[1236]1020      DefPredMapBase(const TR &b) : TR(b) {}
[1116]1021    };
[953]1022   
[1156]1023    ///\brief \ref named-templ-param "Named parameter"
1024    ///function for setting PredMap type
1025    ///
1026    /// \ref named-templ-param "Named parameter"
1027    ///function for setting PredMap type
[1124]1028    ///
[953]1029    template<class T>
[1116]1030    DijkstraWizard<DefPredMapBase<T> > predMap(const T &t)
[953]1031    {
[1193]1032      Base::_pred=(void *)&t;
[1116]1033      return DijkstraWizard<DefPredMapBase<T> >(*this);
[953]1034    }
1035   
[1116]1036    template<class T>
1037    struct DefDistMapBase : public Base {
1038      typedef T DistMap;
[1367]1039      static DistMap *createDistMap(const Graph &) { return 0; };
[1236]1040      DefDistMapBase(const TR &b) : TR(b) {}
[1116]1041    };
[953]1042   
[1156]1043    ///\brief \ref named-templ-param "Named parameter"
1044    ///function for setting DistMap type
1045    ///
1046    /// \ref named-templ-param "Named parameter"
1047    ///function for setting DistMap type
[1124]1048    ///
[953]1049    template<class T>
[1116]1050    DijkstraWizard<DefDistMapBase<T> > distMap(const T &t)
[953]1051    {
[1193]1052      Base::_dist=(void *)&t;
[1116]1053      return DijkstraWizard<DefDistMapBase<T> >(*this);
[953]1054    }
[1117]1055   
[1123]1056    /// Sets the source node, from which the Dijkstra algorithm runs.
1057
1058    /// Sets the source node, from which the Dijkstra algorithm runs.
1059    /// \param s is the source node.
[1117]1060    DijkstraWizard<TR> &source(Node s)
[953]1061    {
[1201]1062      Base::_source=s;
[953]1063      return *this;
1064    }
1065   
1066  };
[255]1067 
[1218]1068  ///Function type interface for Dijkstra algorithm.
[953]1069
[1151]1070  /// \ingroup flowalgs
[1218]1071  ///Function type interface for Dijkstra algorithm.
[953]1072  ///
[1218]1073  ///This function also has several
1074  ///\ref named-templ-func-param "named parameters",
1075  ///they are declared as the members of class \ref DijkstraWizard.
1076  ///The following
1077  ///example shows how to use these parameters.
1078  ///\code
1079  ///  dijkstra(g,length,source).predMap(preds).run();
1080  ///\endcode
1081  ///\warning Don't forget to put the \ref DijkstraWizard::run() "run()"
1082  ///to the end of the parameter list.
1083  ///\sa DijkstraWizard
1084  ///\sa Dijkstra
[953]1085  template<class GR, class LM>
[1116]1086  DijkstraWizard<DijkstraWizardBase<GR,LM> >
1087  dijkstra(const GR &g,const LM &l,typename GR::Node s=INVALID)
[953]1088  {
[1116]1089    return DijkstraWizard<DijkstraWizardBase<GR,LM> >(g,l,s);
[953]1090  }
1091
[921]1092} //END OF NAMESPACE LEMON
[255]1093
1094#endif
Note: See TracBrowser for help on using the repository browser.