Map<Node, Stack<Edge>>
属于
previousEdges
,以便在回溯中跟踪要回溯的边。这个
unwindStack
Edge.cycles
直到它到达终点
Node
这就结束了循环(
loopNode
):
private void labelEdges(Node currentNode, Set<Node> component) {
onStack.put(currentNode, Boolean.TRUE);
for (Edge outEdge : currentNode.getEdges()) {
Node nextNode = outEdge.getEnd();
if (component.contains(nextNode)) {
// put the edge on the previousEdges stack
if (!previousEdges.containsKey(nextNode)) {
previousEdges.put(nextNode, new Stack<>());
}
previousEdges.get(nextNode).push(outEdge);
if (onStack.getOrDefault(nextNode, false)) {
// found loop
unwindStack(nextNode, nextNode);
// pop the previousEdge off the stack, so that we undo any
// overwriting of history for another branch.
previousEdges.get(nextNode).pop();
}
else {
// recursively call this function
labelEdges(nextNode, component);
}
}
}
onStack.put(currentNode, Boolean.FALSE);
}
private void unwindStack(Node currentNode, Node loopNode) {
Edge previousEdge;
try {
previousEdge = previousEdges.get(currentNode).peek();
} catch (EmptyStackException e) {
previousEdge = null;
}
if (previousEdge != null) {
// increment edgeCycles entry by 1
edgeCycles.merge(previousEdge, 1, Integer::sum);
Node previousNode = previousEdge.getStart();
if (previousNode != loopNode) {
unwindStack(previousNode, loopNode);
}
}
}