如何在jgrapht DirectedAcyclicGraph中找到根和叶集
How to find roots and leaves set in jgrapht DirectedAcyclicGraph
我的代码:
import org.jgrapht.graph.DirectedAcyclicGraph;
// ...
private DirectedAcyclicGraph<String, DefaultEdge> graph = new DirectedAcyclicGraph<>(DefaultEdge.class);
// ...
graph.addVertex("x");
graph.addVertex("y");
// ...
graph.addEdge("x", "y");
构建图后,如何得到所有根(没有入边的顶点)和所有叶(没有出边的顶点)的集合
以下是有效的,但我觉得不是最有效的。
// leaves:
graph.vertexSet().stream()
.filter(key -> graph.outgoingEdgesOf(key).size() == 0)
.forEach(key -> doLeavesStuff(key));
// roots:
graph.vertexSet().stream()
.filter(key -> graph.incomingEdgesOf(key).size() == 0)
.forEach(key -> doRootsStuff(key));
不应该是:
// leaves:
graph.vertexSet().stream().filter(
key -> graph.incomingEdgesOf(key).size() == 0
).forEach(
key -> doLeavesStuff(key)
);
// roots:
graph.vertexSet().stream().filter(
key -> graph.outgoingEdgesOf(key).size() == 0
).forEach(
key -> doRootsStuff(key)
);
相反?
我的代码:
import org.jgrapht.graph.DirectedAcyclicGraph;
// ...
private DirectedAcyclicGraph<String, DefaultEdge> graph = new DirectedAcyclicGraph<>(DefaultEdge.class);
// ...
graph.addVertex("x");
graph.addVertex("y");
// ...
graph.addEdge("x", "y");
构建图后,如何得到所有根(没有入边的顶点)和所有叶(没有出边的顶点)的集合
以下是有效的,但我觉得不是最有效的。
// leaves:
graph.vertexSet().stream()
.filter(key -> graph.outgoingEdgesOf(key).size() == 0)
.forEach(key -> doLeavesStuff(key));
// roots:
graph.vertexSet().stream()
.filter(key -> graph.incomingEdgesOf(key).size() == 0)
.forEach(key -> doRootsStuff(key));
不应该是:
// leaves:
graph.vertexSet().stream().filter(
key -> graph.incomingEdgesOf(key).size() == 0
).forEach(
key -> doLeavesStuff(key)
);
// roots:
graph.vertexSet().stream().filter(
key -> graph.outgoingEdgesOf(key).size() == 0
).forEach(
key -> doRootsStuff(key)
);
相反?