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