st_connected.hpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Copyright (C) 2006 The Trustees of Indiana University.
  2. // Use, modification and distribution is subject to the Boost Software
  3. // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
  4. // http://www.boost.org/LICENSE_1_0.txt)
  5. // Authors: Douglas Gregor
  6. // Andrew Lumsdaine
  7. #ifndef BOOST_GRAPH_DISTRIBUTED_ST_CONNECTED_HPP
  8. #define BOOST_GRAPH_DISTRIBUTED_ST_CONNECTED_HPP
  9. #include <boost/graph/graph_traits.hpp>
  10. #include <boost/graph/two_bit_color_map.hpp>
  11. #include <boost/graph/iteration_macros.hpp>
  12. #include <boost/pending/queue.hpp>
  13. namespace boost { namespace graph {
  14. template<typename Graph, typename ColorMap>
  15. bool
  16. st_connected(const Graph& g,
  17. typename graph_traits<Graph>::vertex_descriptor s,
  18. typename graph_traits<Graph>::vertex_descriptor t,
  19. ColorMap color)
  20. {
  21. typedef typename property_traits<ColorMap>::value_type Color;
  22. typedef color_traits<Color> ColorTraits;
  23. typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
  24. // Set all vertices to white (unvisited)
  25. BGL_FORALL_VERTICES_T(v, g, Graph)
  26. put(color, v, ColorTraits::white());
  27. // Vertices found from the source are grey
  28. put(color, s, ColorTraits::gray());
  29. // Vertices found from the target are greeen
  30. put(color, t, ColorTraits::green());
  31. queue<Vertex> Q;
  32. Q.push(s);
  33. Q.push(t);
  34. while (!Q.empty()) {
  35. Vertex u = Q.top(); Q.pop();
  36. Color u_color = get(color, u);
  37. BGL_FORALL_OUTEDGES_T(u, e, g, Graph) {
  38. Vertex v = target(e, g);
  39. Color v_color = get(color, v);
  40. if (v_color == ColorTraits::white()) {
  41. // We have not seen "v" before; mark it with the same color as u
  42. Color u_color = get(color, u);
  43. put(color, v, u_color);
  44. // Push it on the queue
  45. Q.push(v);
  46. } else if (v_color != ColorTraits::black() && u_color != v_color) {
  47. // Colors have collided. We're done!
  48. return true;
  49. }
  50. }
  51. // u is done, so mark it black
  52. put(color, u, ColorTraits::black());
  53. }
  54. return false;
  55. }
  56. template<typename Graph>
  57. inline bool
  58. st_connected(const Graph& g,
  59. typename graph_traits<Graph>::vertex_descriptor s,
  60. typename graph_traits<Graph>::vertex_descriptor t)
  61. {
  62. return st_connected(g, s, t,
  63. make_two_bit_color_map(num_vertices(g),
  64. get(vertex_index, g)));
  65. }
  66. } } // end namespace boost::graph
  67. #endif // BOOST_GRAPH_DISTRIBUTED_ST_CONNECTED_HPP