tiernan_all_cycles.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. // (C) Copyright 2007-2009 Andrew Sutton
  2. //
  3. // Use, modification and distribution are subject to the
  4. // Boost Software License, Version 1.0 (See accompanying file
  5. // LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
  6. #ifndef BOOST_GRAPH_CYCLE_HPP
  7. #define BOOST_GRAPH_CYCLE_HPP
  8. #include <vector>
  9. #include <boost/config.hpp>
  10. #include <boost/graph/graph_concepts.hpp>
  11. #include <boost/graph/graph_traits.hpp>
  12. #include <boost/graph/properties.hpp>
  13. #include <boost/concept/assert.hpp>
  14. #include <boost/concept/detail/concept_def.hpp>
  15. namespace boost
  16. {
  17. namespace concepts
  18. {
  19. BOOST_concept(CycleVisitor, (Visitor)(Path)(Graph))
  20. {
  21. BOOST_CONCEPT_USAGE(CycleVisitor) { vis.cycle(p, g); }
  22. private:
  23. Visitor vis;
  24. Graph g;
  25. Path p;
  26. };
  27. } /* namespace concepts */
  28. using concepts::CycleVisitorConcept;
  29. } /* namespace boost */
  30. #include <boost/concept/detail/concept_undef.hpp>
  31. namespace boost
  32. {
  33. // The implementation of this algorithm is a reproduction of the Teirnan
  34. // approach for directed graphs: bibtex follows
  35. //
  36. // @article{362819,
  37. // author = {James C. Tiernan},
  38. // title = {An efficient search algorithm to find the elementary
  39. // circuits of a graph}, journal = {Commun. ACM}, volume = {13}, number
  40. // = {12}, year = {1970}, issn = {0001-0782}, pages = {722--726}, doi =
  41. // {http://doi.acm.org/10.1145/362814.362819},
  42. // publisher = {ACM Press},
  43. // address = {New York, NY, USA},
  44. // }
  45. //
  46. // It should be pointed out that the author does not provide a complete analysis
  47. // for either time or space. This is in part, due to the fact that it's a fairly
  48. // input sensitive problem related to the density and construction of the graph,
  49. // not just its size.
  50. //
  51. // I've also taken some liberties with the interpretation of the algorithm -
  52. // I've basically modernized it to use real data structures (no more arrays and
  53. // matrices). Oh... and there's explicit control structures - not just gotos.
  54. //
  55. // The problem is definitely NP-complete, an unbounded implementation of this
  56. // will probably run for quite a while on a large graph. The conclusions
  57. // of this paper also reference a Paton algorithm for undirected graphs as being
  58. // much more efficient (apparently based on spanning trees). Although not
  59. // implemented, it can be found here:
  60. //
  61. // @article{363232,
  62. // author = {Keith Paton},
  63. // title = {An algorithm for finding a fundamental set of cycles of a
  64. // graph}, journal = {Commun. ACM}, volume = {12}, number = {9}, year =
  65. // {1969}, issn = {0001-0782}, pages = {514--518}, doi =
  66. // {http://doi.acm.org/10.1145/363219.363232},
  67. // publisher = {ACM Press},
  68. // address = {New York, NY, USA},
  69. // }
  70. /**
  71. * The default cycle visitor provides an empty visit function for cycle
  72. * visitors.
  73. */
  74. struct cycle_visitor
  75. {
  76. template < typename Path, typename Graph >
  77. inline void cycle(const Path& p, const Graph& g)
  78. {
  79. }
  80. };
  81. /**
  82. * The min_max_cycle_visitor simultaneously records the minimum and maximum
  83. * cycles in a graph.
  84. */
  85. struct min_max_cycle_visitor
  86. {
  87. min_max_cycle_visitor(std::size_t& min_, std::size_t& max_)
  88. : minimum(min_), maximum(max_)
  89. {
  90. }
  91. template < typename Path, typename Graph >
  92. inline void cycle(const Path& p, const Graph& g)
  93. {
  94. BOOST_USING_STD_MIN();
  95. BOOST_USING_STD_MAX();
  96. std::size_t len = p.size();
  97. minimum = min BOOST_PREVENT_MACRO_SUBSTITUTION(minimum, len);
  98. maximum = max BOOST_PREVENT_MACRO_SUBSTITUTION(maximum, len);
  99. }
  100. std::size_t& minimum;
  101. std::size_t& maximum;
  102. };
  103. inline min_max_cycle_visitor find_min_max_cycle(
  104. std::size_t& min_, std::size_t& max_)
  105. {
  106. return min_max_cycle_visitor(min_, max_);
  107. }
  108. namespace detail
  109. {
  110. template < typename Graph, typename Path >
  111. inline bool is_vertex_in_path(const Graph&,
  112. typename graph_traits< Graph >::vertex_descriptor v, const Path& p)
  113. {
  114. return (std::find(p.begin(), p.end(), v) != p.end());
  115. }
  116. template < typename Graph, typename ClosedMatrix >
  117. inline bool is_path_closed(const Graph& g,
  118. typename graph_traits< Graph >::vertex_descriptor u,
  119. typename graph_traits< Graph >::vertex_descriptor v,
  120. const ClosedMatrix& closed)
  121. {
  122. // the path from u to v is closed if v can be found in the list
  123. // of closed vertices associated with u.
  124. typedef typename ClosedMatrix::const_reference Row;
  125. Row r = closed[get(vertex_index, g, u)];
  126. if (find(r.begin(), r.end(), v) != r.end())
  127. {
  128. return true;
  129. }
  130. return false;
  131. }
  132. template < typename Graph, typename Path, typename ClosedMatrix >
  133. inline bool can_extend_path(const Graph& g,
  134. typename graph_traits< Graph >::edge_descriptor e, const Path& p,
  135. const ClosedMatrix& m)
  136. {
  137. BOOST_CONCEPT_ASSERT((IncidenceGraphConcept< Graph >));
  138. BOOST_CONCEPT_ASSERT((VertexIndexGraphConcept< Graph >));
  139. typedef typename graph_traits< Graph >::vertex_descriptor Vertex;
  140. // get the vertices in question
  141. Vertex u = source(e, g), v = target(e, g);
  142. // conditions for allowing a traversal along this edge are:
  143. // 1. the index of v must be greater than that at which the
  144. // path is rooted (p.front()).
  145. // 2. the vertex v cannot already be in the path
  146. // 3. the vertex v cannot be closed to the vertex u
  147. bool indices
  148. = get(vertex_index, g, p.front()) < get(vertex_index, g, v);
  149. bool path = !is_vertex_in_path(g, v, p);
  150. bool closed = !is_path_closed(g, u, v, m);
  151. return indices && path && closed;
  152. }
  153. template < typename Graph, typename Path >
  154. inline bool can_wrap_path(const Graph& g, const Path& p)
  155. {
  156. BOOST_CONCEPT_ASSERT((IncidenceGraphConcept< Graph >));
  157. typedef typename graph_traits< Graph >::vertex_descriptor Vertex;
  158. typedef typename graph_traits< Graph >::out_edge_iterator OutIterator;
  159. // iterate over the out-edges of the back, looking for the
  160. // front of the path. also, we can't travel along the same
  161. // edge that we did on the way here, but we don't quite have the
  162. // stringent requirements that we do in can_extend_path().
  163. Vertex u = p.back(), v = p.front();
  164. OutIterator i, end;
  165. for (boost::tie(i, end) = out_edges(u, g); i != end; ++i)
  166. {
  167. if ((target(*i, g) == v))
  168. {
  169. return true;
  170. }
  171. }
  172. return false;
  173. }
  174. template < typename Graph, typename Path, typename ClosedMatrix >
  175. inline typename graph_traits< Graph >::vertex_descriptor extend_path(
  176. const Graph& g, Path& p, ClosedMatrix& closed)
  177. {
  178. BOOST_CONCEPT_ASSERT((IncidenceGraphConcept< Graph >));
  179. typedef typename graph_traits< Graph >::vertex_descriptor Vertex;
  180. typedef typename graph_traits< Graph >::out_edge_iterator OutIterator;
  181. // get the current vertex
  182. Vertex u = p.back();
  183. Vertex ret = graph_traits< Graph >::null_vertex();
  184. // AdjacencyIterator i, end;
  185. OutIterator i, end;
  186. for (boost::tie(i, end) = out_edges(u, g); i != end; ++i)
  187. {
  188. Vertex v = target(*i, g);
  189. // if we can actually extend along this edge,
  190. // then that's what we want to do
  191. if (can_extend_path(g, *i, p, closed))
  192. {
  193. p.push_back(v); // add the vertex to the path
  194. ret = v;
  195. break;
  196. }
  197. }
  198. return ret;
  199. }
  200. template < typename Graph, typename Path, typename ClosedMatrix >
  201. inline bool exhaust_paths(const Graph& g, Path& p, ClosedMatrix& closed)
  202. {
  203. BOOST_CONCEPT_ASSERT((GraphConcept< Graph >));
  204. typedef typename graph_traits< Graph >::vertex_descriptor Vertex;
  205. // if there's more than one vertex in the path, this closes
  206. // of some possible routes and returns true. otherwise, if there's
  207. // only one vertex left, the vertex has been used up
  208. if (p.size() > 1)
  209. {
  210. // get the last and second to last vertices, popping the last
  211. // vertex off the path
  212. Vertex last, prev;
  213. last = p.back();
  214. p.pop_back();
  215. prev = p.back();
  216. // reset the closure for the last vertex of the path and
  217. // indicate that the last vertex in p is now closed to
  218. // the next-to-last vertex in p
  219. closed[get(vertex_index, g, last)].clear();
  220. closed[get(vertex_index, g, prev)].push_back(last);
  221. return true;
  222. }
  223. else
  224. {
  225. return false;
  226. }
  227. }
  228. template < typename Graph, typename Visitor >
  229. inline void all_cycles_from_vertex(const Graph& g,
  230. typename graph_traits< Graph >::vertex_descriptor v, Visitor vis,
  231. std::size_t minlen, std::size_t maxlen)
  232. {
  233. BOOST_CONCEPT_ASSERT((VertexListGraphConcept< Graph >));
  234. typedef typename graph_traits< Graph >::vertex_descriptor Vertex;
  235. typedef std::vector< Vertex > Path;
  236. BOOST_CONCEPT_ASSERT((CycleVisitorConcept< Visitor, Path, Graph >));
  237. typedef std::vector< Vertex > VertexList;
  238. typedef std::vector< VertexList > ClosedMatrix;
  239. Path p;
  240. ClosedMatrix closed(num_vertices(g), VertexList());
  241. Vertex null = graph_traits< Graph >::null_vertex();
  242. // each path investigation starts at the ith vertex
  243. p.push_back(v);
  244. while (1)
  245. {
  246. // extend the path until we've reached the end or the
  247. // maxlen-sized cycle
  248. Vertex j = null;
  249. while (((j = detail::extend_path(g, p, closed)) != null)
  250. && (p.size() < maxlen))
  251. ; // empty loop
  252. // if we're done extending the path and there's an edge
  253. // connecting the back to the front, then we should have
  254. // a cycle.
  255. if (detail::can_wrap_path(g, p) && p.size() >= minlen)
  256. {
  257. vis.cycle(p, g);
  258. }
  259. if (!detail::exhaust_paths(g, p, closed))
  260. {
  261. break;
  262. }
  263. }
  264. }
  265. // Select the minimum allowable length of a cycle based on the directedness
  266. // of the graph - 2 for directed, 3 for undirected.
  267. template < typename D > struct min_cycles
  268. {
  269. enum
  270. {
  271. value = 2
  272. };
  273. };
  274. template <> struct min_cycles< undirected_tag >
  275. {
  276. enum
  277. {
  278. value = 3
  279. };
  280. };
  281. } /* namespace detail */
  282. template < typename Graph, typename Visitor >
  283. inline void tiernan_all_cycles(
  284. const Graph& g, Visitor vis, std::size_t minlen, std::size_t maxlen)
  285. {
  286. BOOST_CONCEPT_ASSERT((VertexListGraphConcept< Graph >));
  287. typedef typename graph_traits< Graph >::vertex_iterator VertexIterator;
  288. VertexIterator i, end;
  289. for (boost::tie(i, end) = vertices(g); i != end; ++i)
  290. {
  291. detail::all_cycles_from_vertex(g, *i, vis, minlen, maxlen);
  292. }
  293. }
  294. template < typename Graph, typename Visitor >
  295. inline void tiernan_all_cycles(const Graph& g, Visitor vis, std::size_t maxlen)
  296. {
  297. typedef typename graph_traits< Graph >::directed_category Dir;
  298. tiernan_all_cycles(g, vis, detail::min_cycles< Dir >::value, maxlen);
  299. }
  300. template < typename Graph, typename Visitor >
  301. inline void tiernan_all_cycles(const Graph& g, Visitor vis)
  302. {
  303. typedef typename graph_traits< Graph >::directed_category Dir;
  304. tiernan_all_cycles(g, vis, detail::min_cycles< Dir >::value,
  305. (std::numeric_limits< std::size_t >::max)());
  306. }
  307. template < typename Graph >
  308. inline std::pair< std::size_t, std::size_t > tiernan_girth_and_circumference(
  309. const Graph& g)
  310. {
  311. std::size_t min_ = (std::numeric_limits< std::size_t >::max)(), max_ = 0;
  312. tiernan_all_cycles(g, find_min_max_cycle(min_, max_));
  313. // if this is the case, the graph is acyclic...
  314. if (max_ == 0)
  315. max_ = min_;
  316. return std::make_pair(min_, max_);
  317. }
  318. template < typename Graph > inline std::size_t tiernan_girth(const Graph& g)
  319. {
  320. return tiernan_girth_and_circumference(g).first;
  321. }
  322. template < typename Graph >
  323. inline std::size_t tiernan_circumference(const Graph& g)
  324. {
  325. return tiernan_girth_and_circumference(g).second;
  326. }
  327. } /* namespace boost */
  328. #endif