COIN-OR::LEMON - Graph Library

source: lemon-0.x/src/lemon/dijkstra.h @ 1151:b217fc69f913

Last change on this file since 1151:b217fc69f913 was 1151:b217fc69f913, checked in by Alpar Juttner, 19 years ago

Several changes in the docs.

File size: 28.4 KB
RevLine 
[906]1/* -*- C++ -*-
[921]2 * src/lemon/dijkstra.h - Part of LEMON, a generic C++ optimization library
[906]3 *
4 * Copyright (C) 2004 Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
5 * (Egervary Combinatorial Optimization Research Group, EGRES).
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.
23
[953]24#include <lemon/list_graph.h>
[921]25#include <lemon/bin_heap.h>
26#include <lemon/invalid.h>
[1119]27#include <lemon/error.h>
28#include <lemon/maps.h>
[255]29
[921]30namespace lemon {
[385]31
[1119]32
[1151]33 
[954]34  ///Default traits class of Dijkstra class.
35
36  ///Default traits class of Dijkstra class.
37  ///\param GR Graph type.
38  ///\param LM Type of length map.
[953]39  template<class GR, class LM>
40  struct DijkstraDefaultTraits
41  {
[954]42    ///The graph type the algorithm runs on.
[953]43    typedef GR Graph;
44    ///The type of the map that stores the edge lengths.
45
[1124]46    ///The type of the map that stores the edge lengths.
[967]47    ///It must meet the \ref concept::ReadMap "ReadMap" concept.
[953]48    typedef LM LengthMap;
[954]49    //The type of the length of the edges.
[987]50    typedef typename LM::Value Value;
[954]51    ///The heap type used by Dijkstra algorithm.
[967]52
53    ///The heap type used by Dijkstra algorithm.
54    ///
55    ///\sa BinHeap
56    ///\sa Dijkstra
[953]57    typedef BinHeap<typename Graph::Node,
[987]58                    typename LM::Value,
[953]59                    typename GR::template NodeMap<int>,
[987]60                    std::less<Value> > Heap;
[953]61
62    ///\brief The type of the map that stores the last
63    ///edges of the shortest paths.
64    ///
[1124]65    ///The type of the map that stores the last
66    ///edges of the shortest paths.
[967]67    ///It must meet the \ref concept::WriteMap "WriteMap" concept.
[953]68    ///
[954]69    typedef typename Graph::template NodeMap<typename GR::Edge> PredMap;
70    ///Instantiates a PredMap.
[953]71 
[1123]72    ///This function instantiates a \ref PredMap.
73    ///\param G is the graph, to which we would like to define the PredMap.
[1119]74    ///\todo The graph alone may be insufficient for the initialization
[954]75    static PredMap *createPredMap(const GR &G)
[953]76    {
77      return new PredMap(G);
78    }
79    ///\brief The type of the map that stores the last but one
80    ///nodes of the shortest paths.
81    ///
[1124]82    ///The type of the map that stores the last but one
83    ///nodes of the shortest paths.
[967]84    ///It must meet the \ref concept::WriteMap "WriteMap" concept.
[953]85    ///
[1130]86    typedef NullMap<typename Graph::Node,typename Graph::Node> PredNodeMap;
[954]87    ///Instantiates a PredNodeMap.
[1125]88   
[1123]89    ///This function instantiates a \ref PredNodeMap.
90    ///\param G is the graph, to which we would like to define the \ref PredNodeMap
[954]91    static PredNodeMap *createPredNodeMap(const GR &G)
[953]92    {
[1130]93      return new PredNodeMap();
[953]94    }
[1119]95
96    ///The type of the map that stores whether a nodes is reached.
97 
[1124]98    ///The type of the map that stores whether a nodes is reached.
[1119]99    ///It must meet the \ref concept::WriteMap "WriteMap" concept.
100    ///By default it is a NullMap.
101    ///\todo If it is set to a real map, Dijkstra::reached() should read this.
102    ///\todo named parameter to set this type, function to read and write.
103    typedef NullMap<typename Graph::Node,bool> ReachedMap;
104    ///Instantiates a ReachedMap.
105 
[1123]106    ///This function instantiates a \ref ReachedMap.
107    ///\param G is the graph, to which we would like to define the \ref ReachedMap
[1119]108    static ReachedMap *createReachedMap(const GR &G)
109    {
110      return new ReachedMap();
111    }
[953]112    ///The type of the map that stores the dists of the nodes.
113 
[1124]114    ///The type of the map that stores the dists of the nodes.
[967]115    ///It must meet the \ref concept::WriteMap "WriteMap" concept.
[953]116    ///
[987]117    typedef typename Graph::template NodeMap<typename LM::Value> DistMap;
[954]118    ///Instantiates a DistMap.
[953]119 
[1123]120    ///This function instantiates a \ref DistMap.
121    ///\param G is the graph, to which we would like to define the \ref DistMap
[954]122    static DistMap *createDistMap(const GR &G)
[953]123    {
124      return new DistMap(G);
125    }
126  };
127 
[255]128  ///%Dijkstra algorithm class.
[1125]129 
[1151]130  /// \ingroup flowalgs
[255]131  ///This class provides an efficient implementation of %Dijkstra algorithm.
132  ///The edge lengths are passed to the algorithm using a
[959]133  ///\ref concept::ReadMap "ReadMap",
[255]134  ///so it is easy to change it to any kind of length.
135  ///
[880]136  ///The type of the length is determined by the
[987]137  ///\ref concept::ReadMap::Value "Value" of the length map.
[255]138  ///
139  ///It is also possible to change the underlying priority heap.
140  ///
[953]141  ///\param GR The graph type the algorithm runs on. The default value is
[955]142  ///\ref ListGraph. The value of GR is not used directly by Dijkstra, it
[954]143  ///is only passed to \ref DijkstraDefaultTraits.
[584]144  ///\param LM This read-only
[385]145  ///EdgeMap
146  ///determines the
147  ///lengths of the edges. It is read once for each edge, so the map
148  ///may involve in relatively time consuming process to compute the edge
149  ///length if it is necessary. The default map type is
[959]150  ///\ref concept::StaticGraph::EdgeMap "Graph::EdgeMap<int>".
[955]151  ///The value of LM is not used directly by Dijkstra, it
[954]152  ///is only passed to \ref DijkstraDefaultTraits.
153  ///\param TR Traits class to set various data types used by the algorithm.
154  ///The default traits class is
[955]155  ///\ref DijkstraDefaultTraits "DijkstraDefaultTraits<GR,LM>".
[954]156  ///See \ref DijkstraDefaultTraits for the documentation of
157  ///a Dijkstra traits class.
[456]158  ///
[689]159  ///\author Jacint Szabo and Alpar Juttner
[1128]160  ///\todo A compare object would be nice.
[584]161
[255]162#ifdef DOXYGEN
[584]163  template <typename GR,
164            typename LM,
[953]165            typename TR>
[255]166#else
[953]167  template <typename GR=ListGraph,
[584]168            typename LM=typename GR::template EdgeMap<int>,
[953]169            typename TR=DijkstraDefaultTraits<GR,LM> >
[255]170#endif
[1116]171  class Dijkstra {
[255]172  public:
[1125]173    /**
174     * \brief \ref Exception for uninitialized parameters.
175     *
176     * This error represents problems in the initialization
177     * of the parameters of the algorithms.
178     */
179    class UninitializedParameter : public lemon::UninitializedParameter {
180    public:
181      virtual const char* exceptionName() const {
182        return "lemon::Dijsktra::UninitializedParameter";
183      }
184    };
[1119]185
[953]186    typedef TR Traits;
[584]187    ///The type of the underlying graph.
[954]188    typedef typename TR::Graph Graph;
[911]189    ///\e
[255]190    typedef typename Graph::Node Node;
[911]191    ///\e
[255]192    typedef typename Graph::NodeIt NodeIt;
[911]193    ///\e
[255]194    typedef typename Graph::Edge Edge;
[911]195    ///\e
[255]196    typedef typename Graph::OutEdgeIt OutEdgeIt;
197   
[584]198    ///The type of the length of the edges.
[987]199    typedef typename TR::LengthMap::Value Value;
[693]200    ///The type of the map that stores the edge lengths.
[954]201    typedef typename TR::LengthMap LengthMap;
[693]202    ///\brief The type of the map that stores the last
[584]203    ///edges of the shortest paths.
[953]204    typedef typename TR::PredMap PredMap;
[693]205    ///\brief The type of the map that stores the last but one
[584]206    ///nodes of the shortest paths.
[953]207    typedef typename TR::PredNodeMap PredNodeMap;
[1119]208    ///The type of the map indicating if a node is reached.
209    typedef typename TR::ReachedMap ReachedMap;
[693]210    ///The type of the map that stores the dists of the nodes.
[953]211    typedef typename TR::DistMap DistMap;
212    ///The heap type used by the dijkstra algorithm.
213    typedef typename TR::Heap Heap;
[255]214  private:
[802]215    /// Pointer to the underlying graph.
[688]216    const Graph *G;
[802]217    /// Pointer to the length map
[954]218    const LengthMap *length;
[802]219    ///Pointer to the map of predecessors edges.
[1119]220    PredMap *_pred;
221    ///Indicates if \ref _pred is locally allocated (\c true) or not.
222    bool local_pred;
[802]223    ///Pointer to the map of predecessors nodes.
[1130]224    PredNodeMap *_predNode;
225    ///Indicates if \ref _predNode is locally allocated (\c true) or not.
226    bool local_predNode;
[802]227    ///Pointer to the map of distances.
[1130]228    DistMap *_dist;
229    ///Indicates if \ref _dist is locally allocated (\c true) or not.
230    bool local_dist;
[1119]231    ///Pointer to the map of reached status of the nodes.
232    ReachedMap *_reached;
233    ///Indicates if \ref _reached is locally allocated (\c true) or not.
234    bool local_reached;
[688]235
[802]236    ///The source node of the last execution.
[774]237    Node source;
238
[1128]239    ///Creates the maps if necessary.
[688]240   
[694]241    ///\todo Error if \c G or are \c NULL. What about \c length?
[688]242    ///\todo Better memory allocation (instead of new).
[1128]243    void create_maps()
[688]244    {
[1119]245      if(!_pred) {
246        local_pred = true;
247        _pred = Traits::createPredMap(*G);
[688]248      }
[1130]249      if(!_predNode) {
250        local_predNode = true;
251        _predNode = Traits::createPredNodeMap(*G);
[688]252      }
[1130]253      if(!_dist) {
254        local_dist = true;
255        _dist = Traits::createDistMap(*G);
[688]256      }
[1119]257      if(!_reached) {
258        local_reached = true;
259        _reached = Traits::createReachedMap(*G);
260      }
[688]261    }
[255]262   
263  public :
[1116]264 
[1128]265    ///\name Named template parameters
266
267    ///@{
268
[953]269    template <class T>
[1116]270    struct DefPredMapTraits : public Traits {
[953]271      typedef T PredMap;
272      static PredMap *createPredMap(const Graph &G)
273      {
[1126]274        throw UninitializedParameter();
[953]275      }
276    };
[954]277    ///\ref named-templ-param "Named parameter" for setting PredMap type
278
279    ///\ref named-templ-param "Named parameter" for setting PredMap type
[1043]280    ///
[953]281    template <class T>
[1116]282    class DefPredMap : public Dijkstra< Graph,
[953]283                                        LengthMap,
[1116]284                                        DefPredMapTraits<T> > { };
[953]285   
286    template <class T>
[1116]287    struct DefPredNodeMapTraits : public Traits {
[953]288      typedef T PredNodeMap;
289      static PredNodeMap *createPredNodeMap(const Graph &G)
290      {
[1126]291        throw UninitializedParameter();
[953]292      }
293    };
[954]294    ///\ref named-templ-param "Named parameter" for setting PredNodeMap type
295
296    ///\ref named-templ-param "Named parameter" for setting PredNodeMap type
[1043]297    ///
[953]298    template <class T>
[1116]299    class DefPredNodeMap : public Dijkstra< Graph,
[953]300                                            LengthMap,
[1116]301                                            DefPredNodeMapTraits<T> > { };
[953]302   
303    template <class T>
[1116]304    struct DefDistMapTraits : public Traits {
[953]305      typedef T DistMap;
306      static DistMap *createDistMap(const Graph &G)
307      {
[1126]308        throw UninitializedParameter();
[953]309      }
310    };
[954]311    ///\ref named-templ-param "Named parameter" for setting DistMap type
312
313    ///\ref named-templ-param "Named parameter" for setting DistMap type
[1043]314    ///
[953]315    template <class T>
[1116]316    class DefDistMap : public Dijkstra< Graph,
[953]317                                        LengthMap,
[1116]318                                        DefDistMapTraits<T> > { };
[953]319   
[1128]320    template <class T>
321    struct DefReachedMapTraits : public Traits {
322      typedef T ReachedMap;
323      static ReachedMap *createReachedMap(const Graph &G)
324      {
325        throw UninitializedParameter();
326      }
327    };
328    ///\ref named-templ-param "Named parameter" for setting ReachedMap type
329
330    ///\ref named-templ-param "Named parameter" for setting ReachedMap type
331    ///
332    template <class T>
333    class DefReachedMap : public Dijkstra< Graph,
334                                        LengthMap,
335                                        DefReachedMapTraits<T> > { };
336   
337    struct DefGraphReachedMapTraits : public Traits {
338      typedef typename Graph::NodeMap<bool> ReachedMap;
339      static ReachedMap *createReachedMap(const Graph &G)
340      {
341        return new ReachedMap(G);
342      }
343    };
344    ///\brief \ref named-templ-param "Named parameter"
345    ///for setting the ReachedMap type to be Graph::NodeMap<bool>.
346    ///
347    ///\ref named-templ-param "Named parameter"
348    ///for setting the ReachedMap type to be Graph::NodeMap<bool>.
349    ///If you don't set it explicitely, it will be automatically allocated.
350    template <class T>
351    class DefReachedMapToBeDefaultMap :
352      public Dijkstra< Graph,
353                       LengthMap,
354                       DefGraphReachedMapTraits> { };
355   
356    ///@}
357
358
359  private:
360    typename Graph::template NodeMap<int> _heap_map;
361    Heap _heap;
362  public:     
363   
[802]364    ///Constructor.
[255]365   
[802]366    ///\param _G the graph the algorithm will run on.
367    ///\param _length the length map used by the algorithm.
[954]368    Dijkstra(const Graph& _G, const LengthMap& _length) :
[688]369      G(&_G), length(&_length),
[1119]370      _pred(NULL), local_pred(false),
[1130]371      _predNode(NULL), local_predNode(false),
372      _dist(NULL), local_dist(false),
[1128]373      _reached(NULL), local_reached(false),
374      _heap_map(*G,-1),_heap(_heap_map)
[688]375    { }
376   
[802]377    ///Destructor.
[688]378    ~Dijkstra()
379    {
[1119]380      if(local_pred) delete _pred;
[1130]381      if(local_predNode) delete _predNode;
382      if(local_dist) delete _dist;
[1119]383      if(local_reached) delete _reached;
[688]384    }
385
386    ///Sets the length map.
387
388    ///Sets the length map.
389    ///\return <tt> (*this) </tt>
[1116]390    Dijkstra &lengthMap(const LengthMap &m)
[688]391    {
392      length = &m;
393      return *this;
394    }
395
396    ///Sets the map storing the predecessor edges.
397
398    ///Sets the map storing the predecessor edges.
399    ///If you don't use this function before calling \ref run(),
400    ///it will allocate one. The destuctor deallocates this
401    ///automatically allocated map, of course.
402    ///\return <tt> (*this) </tt>
[1116]403    Dijkstra &predMap(PredMap &m)
[688]404    {
[1119]405      if(local_pred) {
406        delete _pred;
407        local_pred=false;
[688]408      }
[1119]409      _pred = &m;
[688]410      return *this;
411    }
412
413    ///Sets the map storing the predecessor nodes.
414
415    ///Sets the map storing the predecessor nodes.
416    ///If you don't use this function before calling \ref run(),
417    ///it will allocate one. The destuctor deallocates this
418    ///automatically allocated map, of course.
419    ///\return <tt> (*this) </tt>
[1116]420    Dijkstra &predNodeMap(PredNodeMap &m)
[688]421    {
[1130]422      if(local_predNode) {
423        delete _predNode;
424        local_predNode=false;
[688]425      }
[1130]426      _predNode = &m;
[688]427      return *this;
428    }
429
430    ///Sets the map storing the distances calculated by the algorithm.
431
432    ///Sets the map storing the distances calculated by the algorithm.
433    ///If you don't use this function before calling \ref run(),
434    ///it will allocate one. The destuctor deallocates this
435    ///automatically allocated map, of course.
436    ///\return <tt> (*this) </tt>
[1116]437    Dijkstra &distMap(DistMap &m)
[688]438    {
[1130]439      if(local_dist) {
440        delete _dist;
441        local_dist=false;
[688]442      }
[1130]443      _dist = &m;
[688]444      return *this;
445    }
[694]446
[1130]447  private:
448    void finalizeNodeData(Node v,Value dst)
449    {
450      _reached->set(v,true);
451      _dist->set(v, dst);
452      _predNode->set(v,G->source((*_pred)[v]));
453    }
454
455  public:
[1128]456    ///\name Excetution control
457    ///The simplest way to execute the algorithm is to use
458    ///\ref run().
459    ///\n
460    ///It you need more control on the execution,
461    ///first you must call \ref init(), then you can add several source nodes
462    ///with \ref addSource(). Finally \ref start() will perform the actual path
463    ///computation.
464
465    ///@{
466
467    ///Initializes the internal data structures.
468
469    ///Initializes the internal data structures.
470    ///
471    ///\todo _heap_map's type could also be in the traits class.
472    void init()
473    {
474      create_maps();
[774]475     
476      for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
[1119]477        _pred->set(u,INVALID);
[1130]478        _predNode->set(u,INVALID);
[1119]479        ///\todo *_reached is not set to false.
[1128]480        _heap_map.set(u,Heap::PRE_HEAP);
[694]481      }
[1128]482    }
483   
484    ///Adds a new source node.
485
486    ///Adds a new source node the the priority heap.
487    ///It checks if the node has already been added to the heap.
488    ///
489    ///The optional second parameter is the initial distance of the node.
490    ///
491    ///\todo Do we really want to check it?
492    void addSource(Node s,Value dst=0)
493    {
494      source = s;
495      if(_heap.state(s) != Heap::IN_HEAP) _heap.push(s,dst);
496    }
497   
[1151]498    void processNextNode()
[1128]499    {
500      Node v=_heap.top();
501      Value oldvalue=_heap[v];
502      _heap.pop();
[1130]503      finalizeNodeData(v,oldvalue);
[694]504     
[1128]505      for(OutEdgeIt e(*G,v); e!=INVALID; ++e) {
506        Node w=G->target(e);
507        switch(_heap.state(w)) {
508        case Heap::PRE_HEAP:
509          _heap.push(w,oldvalue+(*length)[e]);
510          _pred->set(w,e);
[1130]511//        _predNode->set(w,v);
[1128]512          break;
513        case Heap::IN_HEAP:
514          if ( oldvalue+(*length)[e] < _heap[w] ) {
515            _heap.decrease(w, oldvalue+(*length)[e]);
[1119]516            _pred->set(w,e);
[1130]517//          _predNode->set(w,v);
[694]518          }
[1128]519          break;
520        case Heap::POST_HEAP:
521          break;
[694]522        }
523      }
524    }
[1128]525
[1130]526    ///Executes the algorithm.
[1128]527
[1130]528    ///Executes the algorithm.
[1128]529    ///
[1130]530    ///\pre init() must be called and at least one node should be added
531    ///with addSource() before using this function.
[1128]532    ///
533    ///This method runs the %Dijkstra algorithm from the root node(s)
534    ///in order to
535    ///compute the
536    ///shortest path to each node. The algorithm computes
537    ///- The shortest path tree.
538    ///- The distance of each node from the root(s).
539    ///
540    void start()
541    {
[1151]542      while ( !_heap.empty() ) processNextNode();
[1128]543    }
[255]544   
[1130]545    ///Executes the algorithm until \c dest is reached.
[1128]546
[1130]547    ///Executes the algorithm until \c dest is reached.
[1128]548    ///
[1130]549    ///\pre init() must be called and at least one node should be added
550    ///with addSource() before using this function.
[1128]551    ///
552    ///This method runs the %Dijkstra algorithm from the root node(s)
553    ///in order to
554    ///compute the
555    ///shortest path to \c dest. The algorithm computes
556    ///- The shortest path to \c  dest.
557    ///- The distance of \c dest from the root(s).
558    ///
559    void start(Node dest)
560    {
[1151]561      while ( !_heap.empty() && _heap.top()!=dest ) processNextNode();
[1130]562      if ( _heap.top()==dest ) finalizeNodeData(_heap.top());
563    }
564   
565    ///Executes the algorithm until a condition is met.
566
567    ///Executes the algorithm until a condition is met.
568    ///
569    ///\pre init() must be called and at least one node should be added
570    ///with addSource() before using this function.
571    ///
572    ///\param nm must be a bool (or convertible) node map. The algorithm
573    ///will stop when it reaches a node \c v with <tt>nm[v]==true</tt>.
574    template<class NM>
575    void start(const NM &nm)
576    {
[1151]577      while ( !_heap.empty() && !mn[_heap.top()] ) processNextNode();
[1130]578      if ( !_heap.empty() ) finalizeNodeData(_heap.top());
[1128]579    }
580   
581    ///Runs %Dijkstra algorithm from node \c s.
582   
583    ///This method runs the %Dijkstra algorithm from a root node \c s
584    ///in order to
585    ///compute the
586    ///shortest path to each node. The algorithm computes
587    ///- The shortest path tree.
588    ///- The distance of each node from the root.
589    ///
590    ///\note d.run(s) is just a shortcut of the following code.
591    ///\code
592    ///  d.init();
593    ///  d.addSource(s);
594    ///  d.start();
595    ///\endcode
596    void run(Node s) {
597      init();
598      addSource(s);
599      start();
600    }
601   
[1130]602    ///Finds the shortest path between \c s and \c t.
603   
604    ///Finds the shortest path between \c s and \c t.
605    ///
606    ///\return The length of the shortest s---t path if there exists one,
607    ///0 otherwise.
608    ///\note Apart from the return value, d.run(s) is
609    ///just a shortcut of the following code.
610    ///\code
611    ///  d.init();
612    ///  d.addSource(s);
613    ///  d.start(t);
614    ///\endcode
615    Value run(Node s,Node t) {
616      init();
617      addSource(s);
618      start(t);
619      return (*_pred)[t]==INVALID?0:(*_dist)[t];
620    }
621   
[1128]622    ///@}
623
624    ///\name Query Functions
625    ///The result of the %Dijkstra algorithm can be obtained using these
626    ///functions.\n
627    ///Before the use of these functions,
628    ///either run() or start() must be called.
629   
630    ///@{
631
[385]632    ///The distance of a node from the root.
[255]633
[385]634    ///Returns the distance of a node from the root.
[255]635    ///\pre \ref run() must be called before using this function.
[385]636    ///\warning If node \c v in unreachable from the root the return value
[255]637    ///of this funcion is undefined.
[1130]638    Value dist(Node v) const { return (*_dist)[v]; }
[373]639
[584]640    ///Returns the 'previous edge' of the shortest path tree.
[255]641
[584]642    ///For a node \c v it returns the 'previous edge' of the shortest path tree,
[785]643    ///i.e. it returns the last edge of a shortest path from the root to \c
[688]644    ///v. It is \ref INVALID
645    ///if \c v is unreachable from the root or if \c v=s. The
[385]646    ///shortest path tree used here is equal to the shortest path tree used in
647    ///\ref predNode(Node v).  \pre \ref run() must be called before using
648    ///this function.
[780]649    ///\todo predEdge could be a better name.
[1119]650    Edge pred(Node v) const { return (*_pred)[v]; }
[373]651
[584]652    ///Returns the 'previous node' of the shortest path tree.
[255]653
[584]654    ///For a node \c v it returns the 'previous node' of the shortest path tree,
[385]655    ///i.e. it returns the last but one node from a shortest path from the
656    ///root to \c /v. It is INVALID if \c v is unreachable from the root or if
657    ///\c v=s. The shortest path tree used here is equal to the shortest path
658    ///tree used in \ref pred(Node v).  \pre \ref run() must be called before
659    ///using this function.
[1130]660    Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
661                                  G->source((*_pred)[v]); }
[255]662   
663    ///Returns a reference to the NodeMap of distances.
664
[385]665    ///Returns a reference to the NodeMap of distances. \pre \ref run() must
666    ///be called before using this function.
[1130]667    const DistMap &distMap() const { return *_dist;}
[385]668 
[255]669    ///Returns a reference to the shortest path tree map.
670
671    ///Returns a reference to the NodeMap of the edges of the
672    ///shortest path tree.
673    ///\pre \ref run() must be called before using this function.
[1119]674    const PredMap &predMap() const { return *_pred;}
[385]675 
676    ///Returns a reference to the map of nodes of shortest paths.
[255]677
678    ///Returns a reference to the NodeMap of the last but one nodes of the
[385]679    ///shortest path tree.
[255]680    ///\pre \ref run() must be called before using this function.
[1130]681    const PredNodeMap &predNodeMap() const { return *_predNode;}
[255]682
[385]683    ///Checks if a node is reachable from the root.
[255]684
[385]685    ///Returns \c true if \c v is reachable from the root.
[1128]686    ///\warning If the algorithm is started from multiple nodes,
687    ///this function may give false result for the source nodes.
[255]688    ///\pre \ref run() must be called before using this function.
[385]689    ///
[1119]690    bool reached(Node v) { return v==source || (*_pred)[v]!=INVALID; }
[255]691   
[1128]692    ///@}
[255]693  };
[953]694
[1123]695  /// Default traits used by \ref DijkstraWizard
696
[1151]697  /// To make it easier to use Dijkstra algorithm
698  ///we have created a wizard class.
699  /// This \ref DijkstraWizard class needs default traits,
700  ///as well as the \ref Dijkstra class.
[1123]701  /// The \ref DijkstraWizardBase is a class to be the default traits of the
702  /// \ref DijkstraWizard class.
[1116]703  template<class GR,class LM>
704  class DijkstraWizardBase : public DijkstraDefaultTraits<GR,LM>
705  {
706
707    typedef DijkstraDefaultTraits<GR,LM> Base;
708  protected:
709    /// Pointer to the underlying graph.
710    void *_g;
711    /// Pointer to the length map
712    void *_length;
713    ///Pointer to the map of predecessors edges.
714    void *_pred;
715    ///Pointer to the map of predecessors nodes.
716    void *_predNode;
717    ///Pointer to the map of distances.
718    void *_dist;
719    ///Pointer to the source node.
720    void *_source;
721
[1123]722    /// Type of the nodes in the graph.
[1116]723    typedef typename Base::Graph::Node Node;
724
725    public:
[1123]726    /// Constructor.
727   
728    /// This constructor does not require parameters, therefore it initiates
729    /// all of the attributes to default values (0, INVALID).
[1116]730    DijkstraWizardBase() : _g(0), _length(0), _pred(0), _predNode(0),
731                       _dist(0), _source(INVALID) {}
732
[1123]733    /// Constructor.
734   
735    /// This constructor requires some parameters, listed in the parameters list.
736    /// Others are initiated to 0.
737    /// \param g is the initial value of  \ref _g
738    /// \param l is the initial value of  \ref _length
739    /// \param s is the initial value of  \ref _source
[1116]740    DijkstraWizardBase(const GR &g,const LM &l, Node s=INVALID) :
741      _g((void *)&g), _length((void *)&l), _pred(0), _predNode(0),
742                  _dist(0), _source((void *)&s) {}
743
744  };
745 
[1123]746  /// A class to make easier the usage of Dijkstra algorithm
[953]747
[1151]748  /// \ingroup flowalgs
[1123]749  /// This class is created to make it easier to use Dijkstra algorithm.
750  /// It uses the functions and features of the plain \ref Dijkstra,
[1151]751  /// but it is much simpler to use it.
[953]752  ///
[1123]753  /// Simplicity means that the way to change the types defined
754  /// in the traits class is based on functions that returns the new class
[1151]755  /// and not on templatable built-in classes.
756  /// When using the plain \ref Dijkstra
757  /// the new class with the modified type comes from
758  /// the original class by using the ::
759  /// operator. In the case of \ref DijkstraWizard only
760  /// a function have to be called and it will
[1123]761  /// return the needed class.
762  ///
763  /// It does not have own \ref run method. When its \ref run method is called
764  /// it initiates a plain \ref Dijkstra class, and calls the \ref Dijkstra::run
765  /// method of it.
[953]766  template<class TR>
[1116]767  class DijkstraWizard : public TR
[953]768  {
[1116]769    typedef TR Base;
[953]770
[1123]771    ///The type of the underlying graph.
[953]772    typedef typename TR::Graph Graph;
[1119]773    //\e
[953]774    typedef typename Graph::Node Node;
[1119]775    //\e
[953]776    typedef typename Graph::NodeIt NodeIt;
[1119]777    //\e
[953]778    typedef typename Graph::Edge Edge;
[1119]779    //\e
[953]780    typedef typename Graph::OutEdgeIt OutEdgeIt;
781   
[1123]782    ///The type of the map that stores the edge lengths.
[953]783    typedef typename TR::LengthMap LengthMap;
[1123]784    ///The type of the length of the edges.
[987]785    typedef typename LengthMap::Value Value;
[1123]786    ///\brief The type of the map that stores the last
787    ///edges of the shortest paths.
[953]788    typedef typename TR::PredMap PredMap;
[1123]789    ///\brief The type of the map that stores the last but one
790    ///nodes of the shortest paths.
[953]791    typedef typename TR::PredNodeMap PredNodeMap;
[1123]792    ///The type of the map that stores the dists of the nodes.
[953]793    typedef typename TR::DistMap DistMap;
794
[1123]795    ///The heap type used by the dijkstra algorithm.
[953]796    typedef typename TR::Heap Heap;
[1116]797public:
[1123]798    /// Constructor.
[1116]799    DijkstraWizard() : TR() {}
[953]800
[1123]801    /// Constructor that requires parameters.
[1124]802
803    /// Constructor that requires parameters.
[1123]804    /// These parameters will be the default values for the traits class.
[1116]805    DijkstraWizard(const Graph &g,const LengthMap &l, Node s=INVALID) :
806      TR(g,l,s) {}
[953]807
[1123]808    ///Copy constructor
[1116]809    DijkstraWizard(const TR &b) : TR(b) {}
[953]810
[1116]811    ~DijkstraWizard() {}
812
[1123]813    ///Runs Dijkstra algorithm from a given node.
814   
815    ///Runs Dijkstra algorithm from a given node.
816    ///The node can be given by the \ref source function.
[1116]817    void run()
[953]818    {
[1126]819      if(_source==0) throw UninitializedParameter();
[1116]820      Dijkstra<Graph,LengthMap,TR> Dij(*(Graph*)_g,*(LengthMap*)_length);
821      if(_pred) Dij.predMap(*(PredMap*)_pred);
822      if(_predNode) Dij.predNodeMap(*(PredNodeMap*)_predNode);
823      if(_dist) Dij.distMap(*(DistMap*)_dist);
824      Dij.run(*(Node*)_source);
825    }
826
[1124]827    ///Runs Dijkstra algorithm from the given node.
[1123]828
[1124]829    ///Runs Dijkstra algorithm from the given node.
[1123]830    ///\param s is the given source.
[1116]831    void run(Node s)
832    {
833      _source=(void *)&s;
834      run();
[953]835    }
836
837    template<class T>
[1116]838    struct DefPredMapBase : public Base {
839      typedef T PredMap;
[1117]840      static PredMap *createPredMap(const Graph &G) { return 0; };
841      DefPredMapBase(const Base &b) : Base(b) {}
[1116]842    };
[953]843   
[1123]844    /// \ref named-templ-param "Named parameter" function for setting PredMap type
845
846    /// \ref named-templ-param "Named parameter" function for setting PredMap type
[1124]847    ///
[953]848    template<class T>
[1116]849    DijkstraWizard<DefPredMapBase<T> > predMap(const T &t)
[953]850    {
[1116]851      _pred=(void *)&t;
852      return DijkstraWizard<DefPredMapBase<T> >(*this);
[953]853    }
854   
[1116]855
[953]856    template<class T>
[1116]857    struct DefPredNodeMapBase : public Base {
858      typedef T PredNodeMap;
[1117]859      static PredNodeMap *createPredNodeMap(const Graph &G) { return 0; };
860      DefPredNodeMapBase(const Base &b) : Base(b) {}
[1116]861    };
862   
[1123]863    /// \ref named-templ-param "Named parameter" function for setting PredNodeMap type
864
865    /// \ref named-templ-param "Named parameter" function for setting PredNodeMap type
[1124]866    ///
[953]867    template<class T>
[1116]868    DijkstraWizard<DefPredNodeMapBase<T> > predNodeMap(const T &t)
[953]869    {
[1116]870      _predNode=(void *)&t;
871      return DijkstraWizard<DefPredNodeMapBase<T> >(*this);
[953]872    }
[1116]873   
874    template<class T>
875    struct DefDistMapBase : public Base {
876      typedef T DistMap;
[1117]877      static DistMap *createDistMap(const Graph &G) { return 0; };
878      DefDistMapBase(const Base &b) : Base(b) {}
[1116]879    };
[953]880   
[1123]881    /// \ref named-templ-param "Named parameter" function for setting DistMap type
882
883    /// \ref named-templ-param "Named parameter" function for setting DistMap type
[1124]884    ///
[953]885    template<class T>
[1116]886    DijkstraWizard<DefDistMapBase<T> > distMap(const T &t)
[953]887    {
[1116]888      _dist=(void *)&t;
889      return DijkstraWizard<DefDistMapBase<T> >(*this);
[953]890    }
[1117]891   
[1123]892    /// Sets the source node, from which the Dijkstra algorithm runs.
893
894    /// Sets the source node, from which the Dijkstra algorithm runs.
895    /// \param s is the source node.
[1117]896    DijkstraWizard<TR> &source(Node s)
[953]897    {
[1116]898      source=(void *)&s;
[953]899      return *this;
900    }
901   
902  };
[255]903 
[953]904  ///\e
905
[1151]906  /// \ingroup flowalgs
[954]907  ///\todo Please document...
[953]908  ///
909  template<class GR, class LM>
[1116]910  DijkstraWizard<DijkstraWizardBase<GR,LM> >
911  dijkstra(const GR &g,const LM &l,typename GR::Node s=INVALID)
[953]912  {
[1116]913    return DijkstraWizard<DijkstraWizardBase<GR,LM> >(g,l,s);
[953]914  }
915
[430]916/// @}
[255]917 
[921]918} //END OF NAMESPACE LEMON
[255]919
920#endif
921
Note: See TracBrowser for help on using the repository browser.