tiernan_all_cycles.hpp 13 KB

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