st_connected.hpp 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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
  14. {
  15. namespace graph
  16. {
  17. template < typename Graph, typename ColorMap >
  18. bool st_connected(const Graph& g,
  19. typename graph_traits< Graph >::vertex_descriptor s,
  20. typename graph_traits< Graph >::vertex_descriptor t, ColorMap color)
  21. {
  22. typedef typename property_traits< ColorMap >::value_type Color;
  23. typedef color_traits< Color > ColorTraits;
  24. typedef typename graph_traits< Graph >::vertex_descriptor Vertex;
  25. // Set all vertices to white (unvisited)
  26. BGL_FORALL_VERTICES_T(v, g, Graph)
  27. put(color, v, ColorTraits::white());
  28. // Vertices found from the source are grey
  29. put(color, s, ColorTraits::gray());
  30. // Vertices found from the target are greeen
  31. put(color, t, ColorTraits::green());
  32. queue< Vertex > Q;
  33. Q.push(s);
  34. Q.push(t);
  35. while (!Q.empty())
  36. {
  37. Vertex u = Q.top();
  38. Q.pop();
  39. Color u_color = get(color, u);
  40. BGL_FORALL_OUTEDGES_T(u, e, g, Graph)
  41. {
  42. Vertex v = target(e, g);
  43. Color v_color = get(color, v);
  44. if (v_color == ColorTraits::white())
  45. {
  46. // We have not seen "v" before; mark it with the same color
  47. // as u
  48. Color u_color = get(color, u);
  49. put(color, v, u_color);
  50. // Push it on the queue
  51. Q.push(v);
  52. }
  53. else if (v_color != ColorTraits::black() && u_color != v_color)
  54. {
  55. // Colors have collided. We're done!
  56. return true;
  57. }
  58. }
  59. // u is done, so mark it black
  60. put(color, u, ColorTraits::black());
  61. }
  62. return false;
  63. }
  64. template < typename Graph >
  65. inline bool st_connected(const Graph& g,
  66. typename graph_traits< Graph >::vertex_descriptor s,
  67. typename graph_traits< Graph >::vertex_descriptor t)
  68. {
  69. return st_connected(g, s, t,
  70. make_two_bit_color_map(num_vertices(g), get(vertex_index, g)));
  71. }
  72. }
  73. } // end namespace boost::graph
  74. #endif // BOOST_GRAPH_DISTRIBUTED_ST_CONNECTED_HPP