I used
class DAG extends jgrapht.graph.DirectedAcyclicGraph <Node,Edge> {
Collection <Node> nodes = collected_for_additional_purposes ();
private int countRoots () {
int count = 0;
for (final Node node : nodes) {
if (inDegreeOf (node) == 0) {
count++;
}
}
return count;
}
}
It's akin to stream used in accepted answer and one could use an iterator too, but the difference here is using inDegreeOf (aVertex)
. Similarly outDegreeOf
would work too.
As an aside, I tried doing the following, but count++
generated compiler error "Local variable count defined in an enclosing scope must be final or effectively final". I'm wondering what a clean, expressive inline syntax might look like.
private int countRoots () {
int count = 0;
nodes.forEach (node -> {
if (inDegreeOf (node) == 0) {
count++;
}
});
return count;
}
https://jgrapht.org/javadoc-1.0.0/org/jgrapht/graph/AbstractBaseGraph.html#inDegreeOf-V-