COIN-OR::LEMON - Graph Library

source: lemon-0.x/lemon/dijkstra.h @ 2458:93b4132ac1e8

Last change on this file since 2458:93b4132ac1e8 was 2443:14abfa02bf42, checked in by Balazs Dezso, 17 years ago

Patch for retrieving reached/processed node in dijkstra, bfs and dfs

Patch from Peter Kovacs

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