1 //
2 //=======================================================================
3 // Copyright 1997, 1998, 1999, 2000 University of Notre Dame.
4 // Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek
5 //
6 // Distributed under the Boost Software License, Version 1.0. (See
7 // accompanying file LICENSE_1_0.txt or copy at
8 // http://www.boost.org/LICENSE_1_0.txt)
9 //=======================================================================
10 //
11 
12 #ifndef BOOST_GRAPH_STRONG_COMPONENTS_HPP
13 #define BOOST_GRAPH_STRONG_COMPONENTS_HPP
14 
15 #include <stack>
16 #include <boost/config.hpp>
17 #include <boost/graph/depth_first_search.hpp>
18 #include <boost/type_traits/conversion_traits.hpp>
19 #include <boost/static_assert.hpp>
20 #include <boost/graph/overloading.hpp>
21 #include <boost/graph/detail/mpi_include.hpp>
22 #include <boost/concept/assert.hpp>
23 
24 namespace boost {
25 
26   //==========================================================================
27   // This is Tarjan's algorithm for strongly connected components
28   // from his paper "Depth first search and linear graph algorithms".
29   // It calculates the components in a single application of DFS.
30   // We implement the algorithm as a dfs-visitor.
31 
32   namespace detail {
33 
34     template <typename ComponentMap, typename RootMap, typename DiscoverTime,
35               typename Stack>
36     class tarjan_scc_visitor : public dfs_visitor<>
37     {
38       typedef typename property_traits<ComponentMap>::value_type comp_type;
39       typedef typename property_traits<DiscoverTime>::value_type time_type;
40     public:
tarjan_scc_visitor(ComponentMap comp_map,RootMap r,DiscoverTime d,comp_type & c_,Stack & s_)41       tarjan_scc_visitor(ComponentMap comp_map, RootMap r, DiscoverTime d,
42                          comp_type& c_, Stack& s_)
43         : c(c_), comp(comp_map), root(r), discover_time(d),
44           dfs_time(time_type()), s(s_) { }
45 
46       template <typename Graph>
discover_vertex(typename graph_traits<Graph>::vertex_descriptor v,const Graph &)47       void discover_vertex(typename graph_traits<Graph>::vertex_descriptor v,
48                            const Graph&) {
49         put(root, v, v);
50         put(comp, v, (std::numeric_limits<comp_type>::max)());
51         put(discover_time, v, dfs_time++);
52         s.push(v);
53       }
54       template <typename Graph>
finish_vertex(typename graph_traits<Graph>::vertex_descriptor v,const Graph & g)55       void finish_vertex(typename graph_traits<Graph>::vertex_descriptor v,
56                          const Graph& g) {
57         typename graph_traits<Graph>::vertex_descriptor w;
58         typename graph_traits<Graph>::out_edge_iterator ei, ei_end;
59         for (boost::tie(ei, ei_end) = out_edges(v, g); ei != ei_end; ++ei) {
60           w = target(*ei, g);
61           if (get(comp, w) == (std::numeric_limits<comp_type>::max)())
62             put(root, v, this->min_discover_time(get(root,v), get(root,w)));
63         }
64         if (get(root, v) == v) {
65           do {
66             w = s.top(); s.pop();
67             put(comp, w, c);
68 	    put(root, w, v);
69           } while (w != v);
70           ++c;
71         }
72       }
73     private:
74       template <typename Vertex>
min_discover_time(Vertex u,Vertex v)75       Vertex min_discover_time(Vertex u, Vertex v) {
76         return get(discover_time, u) < get(discover_time,v) ? u : v;
77       }
78 
79       comp_type& c;
80       ComponentMap comp;
81       RootMap root;
82       DiscoverTime discover_time;
83       time_type dfs_time;
84       Stack& s;
85     };
86 
87     template <class Graph, class ComponentMap, class RootMap,
88               class DiscoverTime, class P, class T, class R>
89     typename property_traits<ComponentMap>::value_type
strong_components_impl(const Graph & g,ComponentMap comp,RootMap root,DiscoverTime discover_time,const bgl_named_params<P,T,R> & params)90     strong_components_impl
91       (const Graph& g,    // Input
92        ComponentMap comp, // Output
93        // Internal record keeping
94        RootMap root,
95        DiscoverTime discover_time,
96        const bgl_named_params<P, T, R>& params)
97     {
98       typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
99       BOOST_CONCEPT_ASSERT(( ReadWritePropertyMapConcept<ComponentMap, Vertex> ));
100       BOOST_CONCEPT_ASSERT(( ReadWritePropertyMapConcept<RootMap, Vertex> ));
101       typedef typename property_traits<RootMap>::value_type RootV;
102       BOOST_CONCEPT_ASSERT(( ConvertibleConcept<RootV, Vertex> ));
103       BOOST_CONCEPT_ASSERT(( ReadWritePropertyMapConcept<DiscoverTime, Vertex> ));
104 
105       typename property_traits<ComponentMap>::value_type total = 0;
106 
107       std::stack<Vertex> s;
108       detail::tarjan_scc_visitor<ComponentMap, RootMap, DiscoverTime,
109         std::stack<Vertex> >
110         vis(comp, root, discover_time, total, s);
111       depth_first_search(g, params.visitor(vis));
112       return total;
113     }
114 
115     //-------------------------------------------------------------------------
116     // The dispatch functions handle the defaults for the rank and discover
117     // time property maps.
118     // dispatch with class specialization to avoid VC++ bug
119 
120     template <class DiscoverTimeMap>
121     struct strong_comp_dispatch2 {
122       template <class Graph, class ComponentMap, class RootMap, class P, class T, class R>
123       inline static typename property_traits<ComponentMap>::value_type
applyboost::detail::strong_comp_dispatch2124       apply(const Graph& g,
125             ComponentMap comp,
126             RootMap r_map,
127             const bgl_named_params<P, T, R>& params,
128             DiscoverTimeMap time_map)
129       {
130         return strong_components_impl(g, comp, r_map, time_map, params);
131       }
132     };
133 
134 
135     template <>
136     struct strong_comp_dispatch2<param_not_found> {
137       template <class Graph, class ComponentMap, class RootMap,
138                 class P, class T, class R>
139       inline static typename property_traits<ComponentMap>::value_type
applyboost::detail::strong_comp_dispatch2140       apply(const Graph& g,
141             ComponentMap comp,
142             RootMap r_map,
143             const bgl_named_params<P, T, R>& params,
144             param_not_found)
145       {
146         typedef typename graph_traits<Graph>::vertices_size_type size_type;
147         size_type       n = num_vertices(g) > 0 ? num_vertices(g) : 1;
148         std::vector<size_type> time_vec(n);
149         return strong_components_impl
150           (g, comp, r_map,
151            make_iterator_property_map(time_vec.begin(), choose_const_pmap
152                                       (get_param(params, vertex_index),
153                                        g, vertex_index), time_vec[0]),
154            params);
155       }
156     };
157 
158     template <class Graph, class ComponentMap, class RootMap,
159               class P, class T, class R, class DiscoverTimeMap>
160     inline typename property_traits<ComponentMap>::value_type
scc_helper2(const Graph & g,ComponentMap comp,RootMap r_map,const bgl_named_params<P,T,R> & params,DiscoverTimeMap time_map)161     scc_helper2(const Graph& g,
162                 ComponentMap comp,
163                 RootMap r_map,
164                 const bgl_named_params<P, T, R>& params,
165                 DiscoverTimeMap time_map)
166     {
167       return strong_comp_dispatch2<DiscoverTimeMap>::apply(g, comp, r_map, params, time_map);
168     }
169 
170     template <class RootMap>
171     struct strong_comp_dispatch1 {
172 
173       template <class Graph, class ComponentMap, class P, class T, class R>
174       inline static typename property_traits<ComponentMap>::value_type
applyboost::detail::strong_comp_dispatch1175       apply(const Graph& g,
176             ComponentMap comp,
177             const bgl_named_params<P, T, R>& params,
178             RootMap r_map)
179       {
180         return scc_helper2(g, comp, r_map, params, get_param(params, vertex_discover_time));
181       }
182     };
183     template <>
184     struct strong_comp_dispatch1<param_not_found> {
185 
186       template <class Graph, class ComponentMap,
187                 class P, class T, class R>
188       inline static typename property_traits<ComponentMap>::value_type
applyboost::detail::strong_comp_dispatch1189       apply(const Graph& g,
190             ComponentMap comp,
191             const bgl_named_params<P, T, R>& params,
192             param_not_found)
193       {
194         typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
195         typename std::vector<Vertex>::size_type
196           n = num_vertices(g) > 0 ? num_vertices(g) : 1;
197         std::vector<Vertex> root_vec(n);
198         return scc_helper2
199           (g, comp,
200            make_iterator_property_map(root_vec.begin(), choose_const_pmap
201                                       (get_param(params, vertex_index),
202                                        g, vertex_index), root_vec[0]),
203            params,
204            get_param(params, vertex_discover_time));
205       }
206     };
207 
208     template <class Graph, class ComponentMap, class RootMap,
209               class P, class T, class R>
210     inline typename property_traits<ComponentMap>::value_type
scc_helper1(const Graph & g,ComponentMap comp,const bgl_named_params<P,T,R> & params,RootMap r_map)211     scc_helper1(const Graph& g,
212                ComponentMap comp,
213                const bgl_named_params<P, T, R>& params,
214                RootMap r_map)
215     {
216       return detail::strong_comp_dispatch1<RootMap>::apply(g, comp, params,
217                                                            r_map);
218     }
219 
220   } // namespace detail
221 
222   template <class Graph, class ComponentMap,
223             class P, class T, class R>
224   inline typename property_traits<ComponentMap>::value_type
strong_components(const Graph & g,ComponentMap comp,const bgl_named_params<P,T,R> & params BOOST_GRAPH_ENABLE_IF_MODELS_PARM (Graph,vertex_list_graph_tag))225   strong_components(const Graph& g, ComponentMap comp,
226                     const bgl_named_params<P, T, R>& params
227                     BOOST_GRAPH_ENABLE_IF_MODELS_PARM(Graph, vertex_list_graph_tag))
228   {
229     typedef typename graph_traits<Graph>::directed_category DirCat;
230     BOOST_STATIC_ASSERT((is_convertible<DirCat*, directed_tag*>::value == true));
231     return detail::scc_helper1(g, comp, params,
232                                get_param(params, vertex_root_t()));
233   }
234 
235   template <class Graph, class ComponentMap>
236   inline typename property_traits<ComponentMap>::value_type
strong_components(const Graph & g,ComponentMap comp BOOST_GRAPH_ENABLE_IF_MODELS_PARM (Graph,vertex_list_graph_tag))237   strong_components(const Graph& g, ComponentMap comp
238                     BOOST_GRAPH_ENABLE_IF_MODELS_PARM(Graph, vertex_list_graph_tag))
239   {
240     typedef typename graph_traits<Graph>::directed_category DirCat;
241     BOOST_STATIC_ASSERT((is_convertible<DirCat*, directed_tag*>::value == true));
242     bgl_named_params<int, int> params(0);
243     return strong_components(g, comp, params);
244   }
245 
246   template <typename Graph, typename ComponentMap, typename ComponentLists>
build_component_lists(const Graph & g,typename graph_traits<Graph>::vertices_size_type num_scc,ComponentMap component_number,ComponentLists & components)247   void build_component_lists
248     (const Graph& g,
249      typename graph_traits<Graph>::vertices_size_type num_scc,
250      ComponentMap component_number,
251      ComponentLists& components)
252   {
253     components.resize(num_scc);
254     typename graph_traits<Graph>::vertex_iterator vi, vi_end;
255     for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)
256       components[component_number[*vi]].push_back(*vi);
257   }
258 
259 
260 } // namespace boost
261 
262 #include <queue>
263 #include <vector>
264 #include <boost/graph/transpose_graph.hpp>
265 #include <boost/pending/indirect_cmp.hpp>
266 #include <boost/graph/connected_components.hpp> // for components_recorder
267 
268 namespace boost {
269 
270   //==========================================================================
271   // This is the version of strongly connected components from
272   // "Intro. to Algorithms" by Cormen, Leiserson, Rivest, which was
273   // adapted from "Data Structure and Algorithms" by Aho, Hopcroft,
274   // and Ullman, who credit the algorithm to S.R. Kosaraju and M. Sharir.
275   // The algorithm is based on computing DFS forests the graph
276   // and its transpose.
277 
278   // This algorithm is slower than Tarjan's by a constant factor, uses
279   // more memory, and puts more requirements on the graph type.
280 
281   template <class Graph, class DFSVisitor, class ComponentsMap,
282             class DiscoverTime, class FinishTime,
283             class ColorMap>
284   typename property_traits<ComponentsMap>::value_type
kosaraju_strong_components(Graph & G,ComponentsMap c,FinishTime finish_time,ColorMap color)285   kosaraju_strong_components(Graph& G, ComponentsMap c,
286                              FinishTime finish_time, ColorMap color)
287   {
288     BOOST_CONCEPT_ASSERT(( MutableGraphConcept<Graph> ));
289     // ...
290 
291     typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
292     typedef typename property_traits<ColorMap>::value_type ColorValue;
293     typedef color_traits<ColorValue> Color;
294     typename property_traits<FinishTime>::value_type time = 0;
295     depth_first_search
296      (G, make_dfs_visitor(stamp_times(finish_time, time, on_finish_vertex())),
297       color);
298 
299     Graph G_T(num_vertices(G));
300     transpose_graph(G, G_T);
301 
302     typedef typename property_traits<ComponentsMap>::value_type count_type;
303 
304     count_type c_count(0);
305     detail::components_recorder<ComponentsMap>
306       vis(c, c_count);
307 
308     // initialize G_T
309     typename graph_traits<Graph>::vertex_iterator ui, ui_end;
310     for (boost::tie(ui, ui_end) = vertices(G_T); ui != ui_end; ++ui)
311       put(color, *ui, Color::white());
312 
313     typedef typename property_traits<FinishTime>::value_type D;
314     typedef indirect_cmp< FinishTime, std::less<D> > Compare;
315 
316     Compare fl(finish_time);
317     std::priority_queue<Vertex, std::vector<Vertex>, Compare > Q(fl);
318 
319     typename graph_traits<Graph>::vertex_iterator i, j, iend, jend;
320     boost::tie(i, iend) = vertices(G_T);
321     boost::tie(j, jend) = vertices(G);
322     for ( ; i != iend; ++i, ++j) {
323       put(finish_time, *i, get(finish_time, *j));
324        Q.push(*i);
325     }
326 
327     while ( !Q.empty() ) {
328       Vertex u = Q.top();
329       Q.pop();
330       if  (get(color, u) == Color::white()) {
331         depth_first_visit(G_T, u, vis, color);
332         ++c_count;
333       }
334     }
335     return c_count;
336   }
337 
338 } // namespace boost
339 
340 #include BOOST_GRAPH_MPI_INCLUDE(<boost/graph/distributed/strong_components.hpp>)
341 
342 #endif // BOOST_GRAPH_STRONG_COMPONENTS_HPP
343