COIN-OR::LEMON - Graph Library

source: lemon-0.x/src/lemon/dijkstra.h @ 1156:91f9236dfec9

Last change on this file since 1156:91f9236dfec9 was 1156:91f9236dfec9, checked in by Alpar Juttner, 19 years ago

Wrap long lines

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