COIN-OR::LEMON - Graph Library

source: lemon-0.x/src/lemon/dijkstra.h @ 1021:fd1d073b6557

Last change on this file since 1021:fd1d073b6557 was 987:87f7c54892df, checked in by Alpar Juttner, 16 years ago

Naming changes:

File size: 10.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
[921]24#include <lemon/bin_heap.h>
25#include <lemon/invalid.h>
[255]26
[921]27namespace lemon {
[385]28
[758]29/// \addtogroup flowalgs
[430]30/// @{
31
[255]32  ///%Dijkstra algorithm class.
33
34  ///This class provides an efficient implementation of %Dijkstra algorithm.
35  ///The edge lengths are passed to the algorithm using a
[959]36  ///\ref concept::ReadMap "ReadMap",
[255]37  ///so it is easy to change it to any kind of length.
38  ///
[880]39  ///The type of the length is determined by the
[987]40  ///\ref concept::ReadMap::Value "Value" of the length map.
[255]41  ///
42  ///It is also possible to change the underlying priority heap.
43  ///
[584]44  ///\param GR The graph type the algorithm runs on.
45  ///\param LM This read-only
[385]46  ///EdgeMap
47  ///determines the
48  ///lengths of the edges. It is read once for each edge, so the map
49  ///may involve in relatively time consuming process to compute the edge
50  ///length if it is necessary. The default map type is
[959]51  ///\ref concept::StaticGraph::EdgeMap "Graph::EdgeMap<int>"
[385]52  ///\param Heap The heap type used by the %Dijkstra
53  ///algorithm. The default
54  ///is using \ref BinHeap "binary heap".
[456]55  ///
[689]56  ///\author Jacint Szabo and Alpar Juttner
[693]57  ///\todo We need a typedef-names should be standardized. (-:
[734]58  ///\todo Type of \c PredMap, \c PredNodeMap and \c DistMap
59  ///should not be fixed. (Problematic to solve).
[584]60
[255]61#ifdef DOXYGEN
[584]62  template <typename GR,
63            typename LM,
[255]64            typename Heap>
65#else
[584]66  template <typename GR,
67            typename LM=typename GR::template EdgeMap<int>,
[532]68            template <class,class,class,class> class Heap = BinHeap >
[255]69#endif
70  class Dijkstra{
71  public:
[584]72    ///The type of the underlying graph.
73    typedef GR Graph;
[911]74    ///\e
[255]75    typedef typename Graph::Node Node;
[911]76    ///\e
[255]77    typedef typename Graph::NodeIt NodeIt;
[911]78    ///\e
[255]79    typedef typename Graph::Edge Edge;
[911]80    ///\e
[255]81    typedef typename Graph::OutEdgeIt OutEdgeIt;
82   
[584]83    ///The type of the length of the edges.
[987]84    typedef typename LM::Value Value;
[693]85    ///The type of the map that stores the edge lengths.
[584]86    typedef LM LengthMap;
[693]87    ///\brief The type of the map that stores the last
[584]88    ///edges of the shortest paths.
[433]89    typedef typename Graph::template NodeMap<Edge> PredMap;
[693]90    ///\brief The type of the map that stores the last but one
[584]91    ///nodes of the shortest paths.
[433]92    typedef typename Graph::template NodeMap<Node> PredNodeMap;
[693]93    ///The type of the map that stores the dists of the nodes.
[987]94    typedef typename Graph::template NodeMap<Value> DistMap;
[255]95
96  private:
[802]97    /// Pointer to the underlying graph.
[688]98    const Graph *G;
[802]99    /// Pointer to the length map
[688]100    const LM *length;
[802]101    ///Pointer to the map of predecessors edges.
[688]102    PredMap *predecessor;
[802]103    ///Indicates if \ref predecessor is locally allocated (\c true) or not.
[688]104    bool local_predecessor;
[802]105    ///Pointer to the map of predecessors nodes.
[688]106    PredNodeMap *pred_node;
[802]107    ///Indicates if \ref pred_node is locally allocated (\c true) or not.
[688]108    bool local_pred_node;
[802]109    ///Pointer to the map of distances.
[688]110    DistMap *distance;
[802]111    ///Indicates if \ref distance is locally allocated (\c true) or not.
[688]112    bool local_distance;
113
[802]114    ///The source node of the last execution.
[774]115    Node source;
116
[785]117    ///Initializes the maps.
[688]118   
[694]119    ///\todo Error if \c G or are \c NULL. What about \c length?
[688]120    ///\todo Better memory allocation (instead of new).
121    void init_maps()
122    {
123      if(!predecessor) {
124        local_predecessor = true;
125        predecessor = new PredMap(*G);
126      }
127      if(!pred_node) {
128        local_pred_node = true;
129        pred_node = new PredNodeMap(*G);
130      }
131      if(!distance) {
132        local_distance = true;
133        distance = new DistMap(*G);
134      }
135    }
[255]136   
137  public :
[802]138    ///Constructor.
[255]139   
[802]140    ///\param _G the graph the algorithm will run on.
141    ///\param _length the length map used by the algorithm.
[584]142    Dijkstra(const Graph& _G, const LM& _length) :
[688]143      G(&_G), length(&_length),
[707]144      predecessor(NULL), local_predecessor(false),
145      pred_node(NULL), local_pred_node(false),
146      distance(NULL), local_distance(false)
[688]147    { }
148   
[802]149    ///Destructor.
[688]150    ~Dijkstra()
151    {
152      if(local_predecessor) delete predecessor;
153      if(local_pred_node) delete pred_node;
154      if(local_distance) delete distance;
155    }
156
157    ///Sets the length map.
158
159    ///Sets the length map.
160    ///\return <tt> (*this) </tt>
161    Dijkstra &setLengthMap(const LM &m)
162    {
163      length = &m;
164      return *this;
165    }
166
167    ///Sets the map storing the predecessor edges.
168
169    ///Sets the map storing the predecessor edges.
170    ///If you don't use this function before calling \ref run(),
171    ///it will allocate one. The destuctor deallocates this
172    ///automatically allocated map, of course.
173    ///\return <tt> (*this) </tt>
174    Dijkstra &setPredMap(PredMap &m)
175    {
176      if(local_predecessor) {
177        delete predecessor;
178        local_predecessor=false;
179      }
180      predecessor = &m;
181      return *this;
182    }
183
184    ///Sets the map storing the predecessor nodes.
185
186    ///Sets the map storing the predecessor nodes.
187    ///If you don't use this function before calling \ref run(),
188    ///it will allocate one. The destuctor deallocates this
189    ///automatically allocated map, of course.
190    ///\return <tt> (*this) </tt>
191    Dijkstra &setPredNodeMap(PredNodeMap &m)
192    {
193      if(local_pred_node) {
194        delete pred_node;
195        local_pred_node=false;
196      }
197      pred_node = &m;
198      return *this;
199    }
200
201    ///Sets the map storing the distances calculated by the algorithm.
202
203    ///Sets the map storing the distances calculated by the algorithm.
204    ///If you don't use this function before calling \ref run(),
205    ///it will allocate one. The destuctor deallocates this
206    ///automatically allocated map, of course.
207    ///\return <tt> (*this) </tt>
208    Dijkstra &setDistMap(DistMap &m)
209    {
210      if(local_distance) {
211        delete distance;
212        local_distance=false;
213      }
214      distance = &m;
215      return *this;
216    }
[255]217   
[694]218  ///Runs %Dijkstra algorithm from node \c s.
219
220  ///This method runs the %Dijkstra algorithm from a root node \c s
221  ///in order to
222  ///compute the
223  ///shortest path to each node. The algorithm computes
224  ///- The shortest path tree.
225  ///- The distance of each node from the root.
226   
227    void run(Node s) {
228     
229      init_maps();
230     
[774]231      source = s;
232     
233      for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
[694]234        predecessor->set(u,INVALID);
235        pred_node->set(u,INVALID);
236      }
237     
238      typename GR::template NodeMap<int> heap_map(*G,-1);
239     
[987]240      typedef Heap<Node, Value, typename GR::template NodeMap<int>,
241      std::less<Value> >
[694]242      HeapType;
243     
244      HeapType heap(heap_map);
245     
246      heap.push(s,0);
247     
248      while ( !heap.empty() ) {
249       
250        Node v=heap.top();
[987]251        Value oldvalue=heap[v];
[694]252        heap.pop();
253        distance->set(v, oldvalue);
254       
255       
[774]256        for(OutEdgeIt e(*G,v); e!=INVALID; ++e) {
[986]257          Node w=G->target(e);
[694]258          switch(heap.state(w)) {
259          case HeapType::PRE_HEAP:
260            heap.push(w,oldvalue+(*length)[e]);
261            predecessor->set(w,e);
262            pred_node->set(w,v);
263            break;
264          case HeapType::IN_HEAP:
265            if ( oldvalue+(*length)[e] < heap[w] ) {
266              heap.decrease(w, oldvalue+(*length)[e]);
267              predecessor->set(w,e);
268              pred_node->set(w,v);
269            }
270            break;
271          case HeapType::POST_HEAP:
272            break;
273          }
274        }
275      }
276    }
[255]277   
[385]278    ///The distance of a node from the root.
[255]279
[385]280    ///Returns the distance of a node from the root.
[255]281    ///\pre \ref run() must be called before using this function.
[385]282    ///\warning If node \c v in unreachable from the root the return value
[255]283    ///of this funcion is undefined.
[987]284    Value dist(Node v) const { return (*distance)[v]; }
[373]285
[584]286    ///Returns the 'previous edge' of the shortest path tree.
[255]287
[584]288    ///For a node \c v it returns the 'previous edge' of the shortest path tree,
[785]289    ///i.e. it returns the last edge of a shortest path from the root to \c
[688]290    ///v. It is \ref INVALID
291    ///if \c v is unreachable from the root or if \c v=s. The
[385]292    ///shortest path tree used here is equal to the shortest path tree used in
293    ///\ref predNode(Node v).  \pre \ref run() must be called before using
294    ///this function.
[780]295    ///\todo predEdge could be a better name.
[688]296    Edge pred(Node v) const { return (*predecessor)[v]; }
[373]297
[584]298    ///Returns the 'previous node' of the shortest path tree.
[255]299
[584]300    ///For a node \c v it returns the 'previous node' of the shortest path tree,
[385]301    ///i.e. it returns the last but one node from a shortest path from the
302    ///root to \c /v. It is INVALID if \c v is unreachable from the root or if
303    ///\c v=s. The shortest path tree used here is equal to the shortest path
304    ///tree used in \ref pred(Node v).  \pre \ref run() must be called before
305    ///using this function.
[688]306    Node predNode(Node v) const { return (*pred_node)[v]; }
[255]307   
308    ///Returns a reference to the NodeMap of distances.
309
[385]310    ///Returns a reference to the NodeMap of distances. \pre \ref run() must
311    ///be called before using this function.
[688]312    const DistMap &distMap() const { return *distance;}
[385]313 
[255]314    ///Returns a reference to the shortest path tree map.
315
316    ///Returns a reference to the NodeMap of the edges of the
317    ///shortest path tree.
318    ///\pre \ref run() must be called before using this function.
[688]319    const PredMap &predMap() const { return *predecessor;}
[385]320 
321    ///Returns a reference to the map of nodes of shortest paths.
[255]322
323    ///Returns a reference to the NodeMap of the last but one nodes of the
[385]324    ///shortest path tree.
[255]325    ///\pre \ref run() must be called before using this function.
[688]326    const PredNodeMap &predNodeMap() const { return *pred_node;}
[255]327
[385]328    ///Checks if a node is reachable from the root.
[255]329
[385]330    ///Returns \c true if \c v is reachable from the root.
[802]331    ///\note The root node is reported to be reached!
[255]332    ///\pre \ref run() must be called before using this function.
[385]333    ///
[780]334    bool reached(Node v) { return v==source || (*predecessor)[v]!=INVALID; }
[255]335   
336  };
337 
[430]338/// @}
[255]339 
[921]340} //END OF NAMESPACE LEMON
[255]341
342#endif
343
344
Note: See TracBrowser for help on using the repository browser.