Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/table_of_contents.html
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ <h1>Table of Contents: the Boost Graph Library
<li>Other Core Algorithms
<ol>
<LI><A href="topological_sort.html"><tt>topological_sort</tt></A>
<LI><A href="topological_sort_levels.html"><tt>topological_sort_levels</tt></A>
<li><a href="transitive_closure.html"><tt>transitive_closure</tt></a>
<li><a href="lengauer_tarjan_dominator.htm"><tt>lengauer_tarjan_dominator_tree</tt></a></li>
</ol>
Expand Down
174 changes: 174 additions & 0 deletions doc/topological_sort_levels.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
<HTML>
<!--
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
-->
<Head>
<Title>Boost Graph Library: Topological Sort into Levels</Title>
<BODY BGCOLOR="#ffffff" LINK="#0000ee" TEXT="#000000" VLINK="#551a8b"
ALINK="#ff0000">
<IMG SRC="../../../boost.png"
ALT="C++ Boost" width="277" height="86">

<BR Clear>


<H1><A NAME="sec:topological-sort-levels">
<TT>topological_sort_levels</TT>
</H1>

<PRE>
// Property-map form. Returns the number of levels.
template &lt;typename VertexListGraph, typename LevelMap&gt;
typename graph_traits&lt;VertexListGraph&gt;::vertices_size_type
topological_sort_levels(const VertexListGraph&amp; g, LevelMap level);

template &lt;typename VertexListGraph, typename LevelMap,
typename P, typename T, typename R&gt;
typename graph_traits&lt;VertexListGraph&gt;::vertices_size_type
topological_sort_levels(const VertexListGraph&amp; g, LevelMap level,
const bgl_named_params&lt;P, T, R&gt;&amp; params = <i>all defaults</i>);

// Convenience form. Fills <tt>levels</tt> so that <tt>levels[k]</tt> contains
// every vertex assigned to level <i>k</i>.
template &lt;typename VertexListGraph&gt;
void topological_sort_levels(const VertexListGraph&amp; g,
std::vector&lt;std::vector&lt;
typename graph_traits&lt;VertexListGraph&gt;::vertex_descriptor&gt; &gt;&amp; levels);

template &lt;typename VertexListGraph, typename P, typename T, typename R&gt;
void topological_sort_levels(const VertexListGraph&amp; g,
std::vector&lt;std::vector&lt;
typename graph_traits&lt;VertexListGraph&gt;::vertex_descriptor&gt; &gt;&amp; levels,
const bgl_named_params&lt;P, T, R&gt;&amp; params = <i>all defaults</i>);
</PRE>

<P>
A variant of <a href="./topological_sort.html"><tt>topological_sort</tt></a>
that groups vertices into levels rather than producing a single linear
ordering. Following BGL's edge convention, an edge <i>(u, v)</i> means <i>u</i>
must precede <i>v</i>; equivalently <i>level(u) &lt; level(v)</i>. Level 0
contains every vertex with no incoming edges. For <i>k &gt; 0</i>, level
<i>k</i> contains every vertex whose deepest predecessor lies at level
<i>k - 1</i>.
</P>

<P>
The graph must be a directed acyclic graph (DAG). If it contains a cycle a
<a href="./exception.html#not_a_dag"><tt>not_a_dag</tt></a> exception is
thrown.
</P>

<P>
Note on direction: <a href="./topological_sort.html"><tt>topological_sort</tt></a>
emits its output in <b>reverse</b> topological order (sinks first when read in
iteration order) and most users reverse the result to consume it forward.
<tt>topological_sort_levels</tt> writes levels forward natively: <tt>levels[0]</tt>
holds the sources and <tt>levels[n-1]</tt> the sinks.
</P>

<P>
The implementation is Kahn's algorithm: it scans out-edges once to compute
in-degrees, then peels off zero-in-degree vertices in waves.
</P>

<h3>Where Defined:</h3>
<a href="../../../boost/graph/topological_sort_levels.hpp"><TT>boost/graph/topological_sort_levels.hpp</TT></a>

<h3>Parameters</h3>

IN: <tt>const VertexListGraph&amp; g</tt>
<blockquote>
A directed acyclic graph (DAG). The graph type must be a model of
<a href="./VertexListGraph.html">Vertex List Graph</a> and
<a href="./IncidenceGraph.html">Incidence Graph</a>.
If the graph is not a DAG, a
<a href="./exception.html#not_a_dag"><tt>not_a_dag</tt></a> exception is
thrown and the contents of the output parameter are unspecified.
</blockquote>

OUT: <tt>LevelMap level</tt>
<blockquote>
After the call, <tt>get(level, v)</tt> is the level of vertex <i>v</i>.
Must be a model of
<a href="../../property_map/doc/ReadWritePropertyMap.html">Read/Write
Property Map</a> whose key type is the graph's vertex descriptor and whose
value type is convertible from
<tt>graph_traits&lt;VertexListGraph&gt;::vertices_size_type</tt>.
</blockquote>

OUT: <tt>std::vector&lt;std::vector&lt;vertex_descriptor&gt; &gt;&amp; levels</tt>
<blockquote>
(Convenience overload.) Resized to hold one inner vector per level. On
return, <tt>levels[k]</tt> contains every vertex at level <i>k</i>. The
order of vertices within a level is unspecified.
</blockquote>

<h3>Named Parameters</h3>

IN: <tt>vertex_index_map(VertexIndexMap i_map)</tt>
<blockquote>
Maps each vertex to an integer in <tt>[0, num_vertices(g))</tt>, used
internally to store running in-degrees. The type must be a model of
<a href="../../property_map/doc/ReadablePropertyMap.html">Readable Property
Map</a> whose key type is the graph's vertex descriptor and whose value
type is an integer.<br>
<b>Default:</b> <tt>get(vertex_index, g)</tt>. If you use this default,
make sure your graph has an internal <tt>vertex_index</tt> property
(e.g. <tt>adjacency_list&lt;…, vecS, …&gt;</tt>).
</blockquote>

<H3>Return Value</H3>

The property-map overloads return the number of levels (one more than the
longest path length in the DAG, or 0 if the graph is empty).

<H3>Complexity</H3>

<i>O(V + E)</i> time and <i>O(V)</i> auxiliary space.

<H3>Example</H3>

<P>
A diamond DAG with edges <i>0 &rarr; 1, 0 &rarr; 2, 1 &rarr; 3, 2 &rarr; 3</i>
has three levels: <i>{0}, {1, 2}, {3}</i>.
</P>

<PRE>
typedef boost::adjacency_list&lt;boost::vecS, boost::vecS, boost::directedS&gt; Graph;
typedef boost::graph_traits&lt;Graph&gt;::vertex_descriptor Vertex;

Graph g(4);
add_edge(0, 1, g);
add_edge(0, 2, g);
add_edge(1, 3, g);
add_edge(2, 3, g);

std::vector&lt;std::vector&lt;Vertex&gt; &gt; levels;
boost::topological_sort_levels(g, levels);

for (std::size_t k = 0; k &lt; levels.size(); ++k) {
std::cout &lt;&lt; "level " &lt;&lt; k &lt;&lt; ":";
for (std::size_t i = 0; i &lt; levels[k].size(); ++i)
std::cout &lt;&lt; ' ' &lt;&lt; levels[k][i];
std::cout &lt;&lt; '\n';
}
</PRE>
The output is:
<PRE>
level 0: 0
level 1: 1 2
level 2: 3
</PRE>

<P>
Motivation:
<a href="https://github.com/boostorg/graph/issues/240">issue&nbsp;#240</a>.
</P>

<br>
<HR>

</BODY>
</HTML>
195 changes: 195 additions & 0 deletions include/boost/graph/topological_sort_levels.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
//
//=======================================================================
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
//
#ifndef BOOST_GRAPH_TOPOLOGICAL_SORT_LEVELS_HPP
#define BOOST_GRAPH_TOPOLOGICAL_SORT_LEVELS_HPP

#include <vector>
#include <boost/config.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/property_map/property_map.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/properties.hpp>
#include <boost/graph/named_function_params.hpp>
#include <boost/graph/exception.hpp>
#include <boost/throw_exception.hpp>

namespace boost
{

// Topological Sort into Levels
//
// Like topological_sort, but groups vertices by "level" rather than producing
// a single linear ordering. Level 0 contains every vertex with no incoming
// edges; level k > 0 contains every vertex whose longest incoming path comes
// from a vertex at level k - 1.
//
// Edge convention follows the rest of BGL: an edge (u, v) means u must
// precede v, so level(u) < level(v). Level numbering runs forward, from
// sources at level 0 to sinks at the highest level.
//
// Implemented via Kahn's algorithm. Same concept requirements as
// topological_sort: VertexListGraph + IncidenceGraph.

namespace detail
{

template < typename VertexListGraph, typename LevelMap,
typename VertexIndexMap >
typename graph_traits< VertexListGraph >::vertices_size_type
topological_sort_levels_impl(
const VertexListGraph& g, LevelMap level, VertexIndexMap index_map)
{
typedef typename graph_traits< VertexListGraph >::vertex_descriptor
Vertex;
typedef typename graph_traits< VertexListGraph >::vertices_size_type
size_type;
typedef typename graph_traits< VertexListGraph >::vertex_iterator
vertex_iter;
typedef typename graph_traits< VertexListGraph >::out_edge_iterator
out_edge_iter;

const size_type n = num_vertices(g);
std::vector< size_type > in_degree(n, 0);

vertex_iter vi, vi_end;
for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)
{
out_edge_iter ei, ei_end;
for (boost::tie(ei, ei_end) = out_edges(*vi, g); ei != ei_end;
++ei)
{
++in_degree[get(index_map, target(*ei, g))];
}
}

std::vector< Vertex > current_level;
for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)
{
if (in_degree[get(index_map, *vi)] == 0)
{
current_level.push_back(*vi);
put(level, *vi, size_type(0));
}
}

size_type total_emitted = current_level.size();
size_type level_count = current_level.empty() ? size_type(0)
: size_type(1);

std::vector< Vertex > next_level;
while (!current_level.empty())
{
next_level.clear();
for (typename std::vector< Vertex >::const_iterator it
= current_level.begin();
it != current_level.end(); ++it)
{
out_edge_iter ei, ei_end;
for (boost::tie(ei, ei_end) = out_edges(*it, g); ei != ei_end;
++ei)
{
Vertex v = target(*ei, g);
size_type vidx = get(index_map, v);
if (--in_degree[vidx] == 0)
{
next_level.push_back(v);
put(level, v, level_count);
}
}
}
if (!next_level.empty())
{
++level_count;
total_emitted += next_level.size();
}
current_level.swap(next_level);
}

if (total_emitted != n)
{
BOOST_THROW_EXCEPTION(not_a_dag());
}

return level_count;
}

template < typename VertexListGraph, typename VertexIndexMap >
void topological_sort_levels_to_buckets(const VertexListGraph& g,
VertexIndexMap index_map,
std::vector< std::vector< typename graph_traits<
VertexListGraph >::vertex_descriptor > >& levels)
{
typedef typename graph_traits< VertexListGraph >::vertices_size_type
size_type;

std::vector< size_type > level_of(num_vertices(g), size_type(0));

const size_type num_levels = topological_sort_levels_impl(g,
make_iterator_property_map(level_of.begin(), index_map),
index_map);

levels.clear();
levels.resize(num_levels);

typename graph_traits< VertexListGraph >::vertex_iterator vi, vi_end;
for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)
{
levels[level_of[get(index_map, *vi)]].push_back(*vi);
}
}

} // namespace detail

// Property-map form. Writes level[v] = k for every vertex v and returns the
// number of levels. LevelMap must be a writable property map keyed on the
// graph's vertex descriptor with a value type convertible from
// vertices_size_type.
template < typename VertexListGraph, typename LevelMap, typename P, typename T,
typename R >
typename graph_traits< VertexListGraph >::vertices_size_type
topological_sort_levels(const VertexListGraph& g, LevelMap level,
const bgl_named_params< P, T, R >& params)
{
return detail::topological_sort_levels_impl(g, level,
choose_const_pmap(get_param(params, vertex_index), g, vertex_index));
}

template < typename VertexListGraph, typename LevelMap >
typename graph_traits< VertexListGraph >::vertices_size_type
topological_sort_levels(const VertexListGraph& g, LevelMap level)
{
return topological_sort_levels(
g, level, bgl_named_params< int, buffer_param_t >(0));
}

// Convenience form. Resizes <tt>levels</tt> to hold one inner vector per
// level; on return, <tt>levels[k]</tt> contains every vertex assigned to
// level k.
template < typename VertexListGraph, typename P, typename T, typename R >
void topological_sort_levels(const VertexListGraph& g,
std::vector< std::vector< typename graph_traits<
VertexListGraph >::vertex_descriptor > >& levels,
const bgl_named_params< P, T, R >& params)
{
detail::topological_sort_levels_to_buckets(g,
choose_const_pmap(get_param(params, vertex_index), g, vertex_index),
levels);
}

template < typename VertexListGraph >
void topological_sort_levels(const VertexListGraph& g,
std::vector< std::vector< typename graph_traits<
VertexListGraph >::vertex_descriptor > >& levels)
{
topological_sort_levels(
g, levels, bgl_named_params< int, buffer_param_t >(0));
}

} // namespace boost

#endif // BOOST_GRAPH_TOPOLOGICAL_SORT_LEVELS_HPP
1 change: 1 addition & 0 deletions test/Jamfile.v2
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ alias graph_test_regular :
[ run delete_edge.cpp ]
[ run johnson-test.cpp ]
[ run lvalue_pmap.cpp ]
[ run topological_sort_levels_test.cpp ]
;

alias graph_test_with_filesystem : :
Expand Down
Loading
Loading