tiernan_all_cycles.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. #include <iostream>
  7. #include <boost/graph/graph_utility.hpp>
  8. #include <boost/graph/undirected_graph.hpp>
  9. #include <boost/graph/directed_graph.hpp>
  10. #include <boost/graph/tiernan_all_cycles.hpp>
  11. #include <boost/graph/erdos_renyi_generator.hpp>
  12. #include <boost/random/linear_congruential.hpp>
  13. using namespace std;
  14. using namespace boost;
  15. struct cycle_validator
  16. {
  17. cycle_validator(size_t& c)
  18. : cycles(c)
  19. { }
  20. template <typename Path, typename Graph>
  21. void cycle(const Path& p, const Graph& g)
  22. {
  23. ++cycles;
  24. // Check to make sure that each of the vertices in the path
  25. // is truly connected and that the back is connected to the
  26. // front - it's not validating that we find all paths, just
  27. // that the paths are valid.
  28. typename Path::const_iterator i, j, last = prior(p.end());
  29. for(i = p.begin(); i != last; ++i) {
  30. j = boost::next(i);
  31. BOOST_ASSERT(edge(*i, *j, g).second);
  32. }
  33. BOOST_ASSERT(edge(p.back(), p.front(), g).second);
  34. }
  35. size_t& cycles;
  36. };
  37. template <typename Graph>
  38. void test()
  39. {
  40. typedef erdos_renyi_iterator<boost::minstd_rand, Graph> er;
  41. // Generate random graphs with 15 vertices and 15% probability
  42. // of edge connection.
  43. static const size_t N = 20;
  44. static const double P = 0.1;
  45. boost::minstd_rand rng;
  46. Graph g(er(rng, N, P), er(), N);
  47. renumber_indices(g);
  48. print_edges(g, get(vertex_index, g));
  49. size_t cycles = 0;
  50. cycle_validator vis(cycles);
  51. tiernan_all_cycles(g, vis);
  52. cout << "# cycles: " << vis.cycles << "\n";
  53. }
  54. int
  55. main(int, char *[])
  56. {
  57. typedef undirected_graph<> Graph;
  58. typedef directed_graph<> DiGraph;
  59. std::cout << "*** undirected ***\n";
  60. test<Graph>();
  61. std::cout << "*** directed ***\n";
  62. test<DiGraph>();
  63. }