Skip to content

Commit 4b20bec

Browse files
committed
Utility to return the max depth of a graph.
1 parent 0f28f3b commit 4b20bec

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

  • src/main/java/org/mastodon/graph/algorithm/util

src/main/java/org/mastodon/graph/algorithm/util/Graphs.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,14 +31,54 @@
3131
import java.util.Comparator;
3232

3333
import org.mastodon.collection.RefList;
34+
import org.mastodon.collection.RefSet;
3435
import org.mastodon.graph.Edge;
36+
import org.mastodon.graph.ReadOnlyGraph;
3537
import org.mastodon.graph.Vertex;
38+
import org.mastodon.graph.algorithm.RootFinder;
39+
import org.mastodon.graph.algorithm.traversal.DepthFirstIterator;
3640

3741
/**
3842
* A collection of utilities to assist with graph manipulation.
3943
*/
4044
public class Graphs
4145
{
46+
47+
/**
48+
* Returns the max depth of the graph, i.e. the maximum number of branching
49+
* points on any path from a root to a leaf, when iterating depth-first, in
50+
* a directed manner.
51+
*
52+
* @param <V>
53+
* the vertex type
54+
* @param <E>
55+
* the edge type
56+
* @param graph
57+
* the graph to analyze.
58+
* @return the max depth of the graph.
59+
*/
60+
public static < V extends Vertex< E >, E extends Edge< V > > int maxDepth( final ReadOnlyGraph< V, E > graph )
61+
{
62+
final DepthFirstIterator< V, E > it = new DepthFirstIterator<>( graph );
63+
final RefSet< V > roots = RootFinder.getRoots( graph );
64+
int maxDepth = 0;
65+
for ( final V root : roots )
66+
{
67+
it.reset( root );
68+
int depth = 0;
69+
while ( it.hasNext() )
70+
{
71+
final V v = it.next();
72+
if ( v.outgoingEdges().size() > 1 )
73+
depth++;
74+
}
75+
if ( depth > maxDepth )
76+
maxDepth = depth;
77+
78+
}
79+
return maxDepth;
80+
}
81+
4282
/**
4383
* Gets the vertex opposite another vertex across an edge.
4484
* <p>

0 commit comments

Comments
 (0)