Moved the gui to glemon/trunk.
3 * This file is a part of LEMON, a generic C++ optimization library
5 * Copyright (C) 2003-2006
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
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.
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
19 #ifndef LEMON_FLOYD_WARSHALL_H
20 #define LEMON_FLOYD_WARSHALL_H
24 /// \brief FloydWarshall algorithm.
27 #include <lemon/list_graph.h>
28 #include <lemon/graph_utils.h>
29 #include <lemon/bits/invalid.h>
30 #include <lemon/error.h>
31 #include <lemon/matrix_maps.h>
32 #include <lemon/maps.h>
38 /// \brief Default OperationTraits for the FloydWarshall algorithm class.
40 /// It defines all computational operations and constants which are
41 /// used in the Floyd-Warshall algorithm. The default implementation
42 /// is based on the numeric_limits class. If the numeric type does not
43 /// have infinity value then the maximum value is used as extremal
47 bool has_infinity = std::numeric_limits<Value>::has_infinity>
48 struct FloydWarshallDefaultOperationTraits {
49 /// \brief Gives back the zero value of the type.
51 return static_cast<Value>(0);
53 /// \brief Gives back the positive infinity value of the type.
54 static Value infinity() {
55 return std::numeric_limits<Value>::infinity();
57 /// \brief Gives back the sum of the given two elements.
58 static Value plus(const Value& left, const Value& right) {
61 /// \brief Gives back true only if the first value less than the second.
62 static bool less(const Value& left, const Value& right) {
67 template <typename Value>
68 struct FloydWarshallDefaultOperationTraits<Value, false> {
70 return static_cast<Value>(0);
72 static Value infinity() {
73 return std::numeric_limits<Value>::max();
75 static Value plus(const Value& left, const Value& right) {
76 if (left == infinity() || right == infinity()) return infinity();
79 static bool less(const Value& left, const Value& right) {
84 /// \brief Default traits class of FloydWarshall class.
86 /// Default traits class of FloydWarshall class.
87 /// \param _Graph Graph type.
88 /// \param _LegthMap Type of length map.
89 template<class _Graph, class _LengthMap>
90 struct FloydWarshallDefaultTraits {
91 /// The graph type the algorithm runs on.
94 /// \brief The type of the map that stores the edge lengths.
96 /// The type of the map that stores the edge lengths.
97 /// It must meet the \ref concept::ReadMap "ReadMap" concept.
98 typedef _LengthMap LengthMap;
100 // The type of the length of the edges.
101 typedef typename _LengthMap::Value Value;
103 /// \brief Operation traits for floyd-warshall algorithm.
105 /// It defines the infinity type on the given Value type
106 /// and the used operation.
107 /// \see FloydWarshallDefaultOperationTraits
108 typedef FloydWarshallDefaultOperationTraits<Value> OperationTraits;
110 /// \brief The type of the matrix map that stores the last edges of the
113 /// The type of the map that stores the last edges of the shortest paths.
114 /// It must be a matrix map with \c Graph::Edge value type.
116 typedef DynamicMatrixMap<Graph, typename Graph::Node,
117 typename Graph::Edge> PredMap;
119 /// \brief Instantiates a PredMap.
121 /// This function instantiates a \ref PredMap.
122 /// \param graph is the graph,
123 /// to which we would like to define the PredMap.
124 /// \todo The graph alone may be insufficient for the initialization
125 static PredMap *createPredMap(const _Graph& graph) {
126 return new PredMap(graph);
129 /// \brief The type of the map that stores the dists of the nodes.
131 /// The type of the map that stores the dists of the nodes.
132 /// It must meet the \ref concept::WriteMatrixMap "WriteMatrixMap" concept.
134 typedef DynamicMatrixMap<Graph, typename Graph::Node, Value> DistMap;
136 /// \brief Instantiates a DistMap.
138 /// This function instantiates a \ref DistMap.
139 /// \param graph is the graph, to which we would like to define the
141 static DistMap *createDistMap(const _Graph& graph) {
142 return new DistMap(graph);
147 /// \brief %FloydWarshall algorithm class.
149 /// \ingroup flowalgs
150 /// This class provides an efficient implementation of \c Floyd-Warshall
151 /// algorithm. The edge lengths are passed to the algorithm using a
152 /// \ref concept::ReadMap "ReadMap", so it is easy to change it to any
155 /// The algorithm solves the shortest path problem for each pair
156 /// of node when the edges can have negative length but the graph should
157 /// not contain cycles with negative sum of length. If we can assume
158 /// that all edge is non-negative in the graph then the dijkstra algorithm
159 /// should be used from each node rather and if the graph is sparse and
160 /// there are negative circles then the johnson algorithm.
162 /// The complexity of this algorithm is \f$ O(n^3+e) \f$.
164 /// The type of the length is determined by the
165 /// \ref concept::ReadMap::Value "Value" of the length map.
167 /// \param _Graph The graph type the algorithm runs on. The default value
168 /// is \ref ListGraph. The value of _Graph is not used directly by
169 /// FloydWarshall, it is only passed to \ref FloydWarshallDefaultTraits.
170 /// \param _LengthMap This read-only EdgeMap determines the lengths of the
171 /// edges. It is read once for each edge, so the map may involve in
172 /// relatively time consuming process to compute the edge length if
173 /// it is necessary. The default map type is \ref
174 /// concept::StaticGraph::EdgeMap "Graph::EdgeMap<int>". The value
175 /// of _LengthMap is not used directly by FloydWarshall, it is only passed
176 /// to \ref FloydWarshallDefaultTraits. \param _Traits Traits class to set
177 /// various data types used by the algorithm. The default traits
178 /// class is \ref FloydWarshallDefaultTraits
179 /// "FloydWarshallDefaultTraits<_Graph,_LengthMap>". See \ref
180 /// FloydWarshallDefaultTraits for the documentation of a FloydWarshall
183 /// \author Balazs Dezso
186 template <typename _Graph, typename _LengthMap typename _Traits >
188 template <typename _Graph=ListGraph,
189 typename _LengthMap=typename _Graph::template EdgeMap<int>,
190 typename _Traits=FloydWarshallDefaultTraits<_Graph,_LengthMap> >
192 class FloydWarshall {
195 /// \brief \ref Exception for uninitialized parameters.
197 /// This error represents problems in the initialization
198 /// of the parameters of the algorithms.
200 class UninitializedParameter : public lemon::UninitializedParameter {
202 virtual const char* exceptionName() const {
203 return "lemon::FloydWarshall::UninitializedParameter";
207 typedef _Traits Traits;
208 ///The type of the underlying graph.
209 typedef typename _Traits::Graph Graph;
211 typedef typename Graph::Node Node;
212 typedef typename Graph::NodeIt NodeIt;
213 typedef typename Graph::Edge Edge;
214 typedef typename Graph::EdgeIt EdgeIt;
216 /// \brief The type of the length of the edges.
217 typedef typename _Traits::LengthMap::Value Value;
218 /// \brief The type of the map that stores the edge lengths.
219 typedef typename _Traits::LengthMap LengthMap;
220 /// \brief The type of the map that stores the last
221 /// edges of the shortest paths. The type of the PredMap
222 /// is a matrix map for Edges
223 typedef typename _Traits::PredMap PredMap;
224 /// \brief The type of the map that stores the dists of the nodes.
225 /// The type of the DistMap is a matrix map for Values
226 typedef typename _Traits::DistMap DistMap;
227 /// \brief The operation traits.
228 typedef typename _Traits::OperationTraits OperationTraits;
230 /// Pointer to the underlying graph.
232 /// Pointer to the length map
233 const LengthMap *length;
234 ///Pointer to the map of predecessors edges.
236 ///Indicates if \ref _pred is locally allocated (\c true) or not.
238 ///Pointer to the map of distances.
240 ///Indicates if \ref _dist is locally allocated (\c true) or not.
243 /// Creates the maps if necessary.
247 _pred = Traits::createPredMap(*graph);
251 _dist = Traits::createDistMap(*graph);
257 /// \name Named template parameters
262 struct DefPredMapTraits : public Traits {
264 static PredMap *createPredMap(const Graph& graph) {
265 throw UninitializedParameter();
269 /// \brief \ref named-templ-param "Named parameter" for setting PredMap
271 /// \ref named-templ-param "Named parameter" for setting PredMap type
275 : public FloydWarshall< Graph, LengthMap, DefPredMapTraits<T> > {
276 typedef FloydWarshall< Graph, LengthMap, DefPredMapTraits<T> > Create;
280 struct DefDistMapTraits : public Traits {
282 static DistMap *createDistMap(const Graph& graph) {
283 throw UninitializedParameter();
286 /// \brief \ref named-templ-param "Named parameter" for setting DistMap
289 /// \ref named-templ-param "Named parameter" for setting DistMap type
293 : public FloydWarshall< Graph, LengthMap, DefDistMapTraits<T> > {
294 typedef FloydWarshall< Graph, LengthMap, DefDistMapTraits<T> > Create;
298 struct DefOperationTraitsTraits : public Traits {
299 typedef T OperationTraits;
302 /// \brief \ref named-templ-param "Named parameter" for setting
303 /// OperationTraits type
305 /// \ref named-templ-param "Named parameter" for setting PredMap type
307 struct DefOperationTraits
308 : public FloydWarshall< Graph, LengthMap, DefOperationTraitsTraits<T> > {
309 typedef FloydWarshall< Graph, LengthMap, DefOperationTraitsTraits<T> >
321 typedef FloydWarshall Create;
323 /// \brief Constructor.
325 /// \param _graph the graph the algorithm will run on.
326 /// \param _length the length map used by the algorithm.
327 FloydWarshall(const Graph& _graph, const LengthMap& _length) :
328 graph(&_graph), length(&_length),
329 _pred(0), local_pred(false),
330 _dist(0), local_dist(false) {}
334 if(local_pred) delete _pred;
335 if(local_dist) delete _dist;
338 /// \brief Sets the length map.
340 /// Sets the length map.
341 /// \return \c (*this)
342 FloydWarshall &lengthMap(const LengthMap &m) {
347 /// \brief Sets the map storing the predecessor edges.
349 /// Sets the map storing the predecessor edges.
350 /// If you don't use this function before calling \ref run(),
351 /// it will allocate one. The destuctor deallocates this
352 /// automatically allocated map, of course.
353 /// \return \c (*this)
354 FloydWarshall &predMap(PredMap &m) {
363 /// \brief Sets the map storing the distances calculated by the algorithm.
365 /// Sets the map storing the distances calculated by the algorithm.
366 /// If you don't use this function before calling \ref run(),
367 /// it will allocate one. The destuctor deallocates this
368 /// automatically allocated map, of course.
369 /// \return \c (*this)
370 FloydWarshall &distMap(DistMap &m) {
379 ///\name Execution control
380 /// The simplest way to execute the algorithm is to use
381 /// one of the member functions called \c run(...).
383 /// If you need more control on the execution,
384 /// Finally \ref start() will perform the actual path
389 /// \brief Initializes the internal data structures.
391 /// Initializes the internal data structures.
394 for (NodeIt it(*graph); it != INVALID; ++it) {
395 for (NodeIt jt(*graph); jt != INVALID; ++jt) {
396 _pred->set(it, jt, INVALID);
397 _dist->set(it, jt, OperationTraits::infinity());
399 _dist->set(it, it, OperationTraits::zero());
401 for (EdgeIt it(*graph); it != INVALID; ++it) {
402 Node source = graph->source(it);
403 Node target = graph->target(it);
404 if (OperationTraits::less((*length)[it], (*_dist)(source, target))) {
405 _dist->set(source, target, (*length)[it]);
406 _pred->set(source, target, it);
411 /// \brief Executes the algorithm.
413 /// This method runs the %FloydWarshall algorithm in order to compute
414 /// the shortest path to each node pairs. The algorithm
416 /// - The shortest path tree for each node.
417 /// - The distance between each node pairs.
419 for (NodeIt kt(*graph); kt != INVALID; ++kt) {
420 for (NodeIt it(*graph); it != INVALID; ++it) {
421 for (NodeIt jt(*graph); jt != INVALID; ++jt) {
422 Value relaxed = OperationTraits::plus((*_dist)(it, kt),
424 if (OperationTraits::less(relaxed, (*_dist)(it, jt))) {
425 _dist->set(it, jt, relaxed);
426 _pred->set(it, jt, (*_pred)(kt, jt));
433 /// \brief Executes the algorithm and checks the negative cycles.
435 /// This method runs the %FloydWarshall algorithm in order to compute
436 /// the shortest path to each node pairs. If there is a negative cycle
437 /// in the graph it gives back false.
438 /// The algorithm computes
439 /// - The shortest path tree for each node.
440 /// - The distance between each node pairs.
441 bool checkedStart() {
443 for (NodeIt it(*graph); it != INVALID; ++it) {
444 if (OperationTraits::less((*dist)(it, it), OperationTraits::zero())) {
451 /// \brief Runs %FloydWarshall algorithm.
453 /// This method runs the %FloydWarshall algorithm from a each node
454 /// in order to compute the shortest path to each node pairs.
455 /// The algorithm computes
456 /// - The shortest path tree for each node.
457 /// - The distance between each node pairs.
459 /// \note d.run(s) is just a shortcut of the following code.
471 /// \name Query Functions
472 /// The result of the %FloydWarshall algorithm can be obtained using these
474 /// Before the use of these functions,
475 /// either run() or start() must be called.
479 /// \brief Copies the shortest path to \c t into \c p
481 /// This function copies the shortest path to \c t into \c p.
482 /// If it \c t is a source itself or unreachable, then it does not
484 /// \return Returns \c true if a path to \c t was actually copied to \c p,
485 /// \c false otherwise.
487 template <typename Path>
488 bool getPath(Path &p, Node source, Node target) {
489 if (connected(source, target)) {
491 typename Path::Builder b(target);
492 for(b.setStartNode(target); predEdge(source, target) != INVALID;
493 target = predNode(target)) {
494 b.pushFront(predEdge(source, target));
502 /// \brief The distance between two nodes.
504 /// Returns the distance between two nodes.
505 /// \pre \ref run() must be called before using this function.
506 /// \warning If node \c v in unreachable from the root the return value
507 /// of this funcion is undefined.
508 Value dist(Node source, Node target) const {
509 return (*_dist)(source, target);
512 /// \brief Returns the 'previous edge' of the shortest path tree.
514 /// For the node \c node it returns the 'previous edge' of the shortest
515 /// path tree to direction of the node \c root
516 /// i.e. it returns the last edge of a shortest path from the node \c root
517 /// to \c node. It is \ref INVALID if \c node is unreachable from the root
518 /// or if \c node=root. The shortest path tree used here is equal to the
519 /// shortest path tree used in \ref predNode().
520 /// \pre \ref run() must be called before using this function.
521 Edge predEdge(Node root, Node node) const {
522 return (*_pred)(root, node);
525 /// \brief Returns the 'previous node' of the shortest path tree.
527 /// For a node \c node it returns the 'previous node' of the shortest path
528 /// tree to direction of the node \c root, i.e. it returns the last but
529 /// one node from a shortest path from the \c root to \c node. It is
530 /// INVALID if \c node is unreachable from the root or if \c node=root.
531 /// The shortest path tree used here is equal to the
532 /// shortest path tree used in \ref predEdge().
533 /// \pre \ref run() must be called before using this function.
534 Node predNode(Node root, Node node) const {
535 return (*_pred)(root, node) == INVALID ?
536 INVALID : graph->source((*_pred)(root, node));
539 /// \brief Returns a reference to the matrix node map of distances.
541 /// Returns a reference to the matrix node map of distances.
543 /// \pre \ref run() must be called before using this function.
544 const DistMap &distMap() const { return *_dist;}
546 /// \brief Returns a reference to the shortest path tree map.
548 /// Returns a reference to the matrix node map of the edges of the
549 /// shortest path tree.
550 /// \pre \ref run() must be called before using this function.
551 const PredMap &predMap() const { return *_pred;}
553 /// \brief Checks if a node is reachable from the root.
555 /// Returns \c true if \c v is reachable from the root.
556 /// \pre \ref run() must be called before using this function.
558 bool connected(Node source, Node target) {
559 return (*_dist)(source, target) != OperationTraits::infinity();
565 } //END OF NAMESPACE LEMON