3.1 Find the groups of nodes that reach each other
You divide a graph into its strongly connected components, see which of them contain a cycle, and check whether two given nodes are in the same one.
Problem
Section titled “Problem”You want to find the nodes of a graph that depend on each other, directly or through other nodes. In the graph, these are groups of nodes in which every node reaches every other along a path of edges. If no further node can join such a group, it is an SCC. It usually has to be handled as a whole. You need this for:
- packages or modules that use each other: they cannot be built, tested or released one by one;
- functions that call each other in a cycle: they are mutually recursive, and an analysis of one of them must take all of them into account;
- processes that wait for each other in a cycle: they are in a deadlock.
Example
Section titled “Example”The example is the grammar of a small programming language:
program = { statement } ;statement = block | ifStatement | assignment ;block = "{" { statement } "}" ;ifStatement = "if" "(" expression ")" statement ;assignment = name "=" expression ";" ;expression = term { "+" term } ;term = factor { "*" factor } ;factor = number | name | "(" expression ")" ;name and number are rules for single tokens. The example graph rules models how the rules use
each other. It has an edge from each rule to each rule it uses. The array names holds the names of
the rules. A tool for grammars needs to know which rules are recursive, and with which other rules.
A parser for the grammar needs recursion exactly there. Properties such as “which tokens can a rule
start with?” have to be computed for such rules together. Which rules reach each other? The SCCs of
the graph answer it. Two of them contain a cycle: the statements, which contain statements, and the
expressions, which contain expressions. Every other rule is an SCC of its own. The picture after
shows the two SCCs with a cycle as green frames, and the edges that lie on their cycles in orange.
- Rule asked about
- Edge on a cycle
- SCC with a cycle
Solution
Section titled “Solution”Components.sccsOfcomponents::sccs_ofComponents.sccsOfComponents.SccsOf finds the SCCs. Its result of type SccsSccsSccsSccs
answers the questions about them:
// Group the rules into SCCs: rules in one SCC use each other, directly or through// others.Sccs sccs = Components.sccsOf(rules);int sccCount = sccs.sccCount(); // 6
// Keep the SCCs with a cycle: those are the rules that use themselves, through each// other.List<List<String>> recursive = new ArrayList<>();for (int scc = 0; scc < sccs.sccCount(); scc++) { if (sccs.containsCycle(scc)) { recursive.add( sccs.nodesOf(scc).intStream().mapToObj(rule -> names[rule]).toList()); }}// recursive: [[expression, term, factor], [statement, block, ifStatement]]// Group the rules into SCCs: rules in one SCC use each other, directly or through// others.let sccs = components::sccs_of(&rules);let scc_count = sccs.scc_count(); // 6
// Keep the SCCs with a cycle: those are the rules that use themselves, through each// other.let recursive: Vec<Vec<&str>> = (0..scc_count) .filter(|&scc| sccs.contains_cycle(scc)) .map(|scc| { sccs.nodes_of(scc) .iter() .map(|&rule| names[rule as usize]) .collect() }) .collect();// recursive: [["expression", "term", "factor"],// ["statement", "block", "ifStatement"]]// Group the rules into SCCs: rules in one SCC use each other, directly or through// others.const sccs = Components.sccsOf(rules);const sccCount = sccs.sccCount; // 6
// Keep the SCCs with a cycle: those are the rules that use themselves, through each// other.const recursive: string[][] = [];for (let scc = 0; scc < sccs.sccCount; scc++) { if (sccs.containsCycle(scc)) { recursive.push(Array.from(sccs.nodesOf(scc), (rule) => names[rule])); }}// recursive: [[expression, term, factor], [statement, block, ifStatement]]// Group the rules into SCCs: rules in one SCC use each other, directly or through// others.Sccs sccs = Components.SccsOf(rules);int sccCount = sccs.SccCount; // 6
// Keep the SCCs with a cycle: those are the rules that use themselves, through// each other.List<List<string>> recursive = [];for (int scc = 0; scc < sccs.SccCount; scc++){ if (sccs.ContainsCycle(scc)) { recursive.Add([.. sccs.NodesOf(scc).Select(rule => names[rule])]); }}// recursive: [[expression, term, factor], [statement, block, ifStatement]]There are 6 SCCs. Each has an SCC ID, from 0 to 5. Sccs.containsCycleSccs::contains_cycleSccs.containsCycleSccs.ContainsCycle picks the
two with a cycle. NodePartition.nodesOfNodePartition::nodes_ofNodePartition.nodesOfNodePartition.NodesOf returns the nodes of each in ascending
order, which gives the two groups of the picture after. To find out whether two given rules reach
each other, compare their SCCs with Sccs.sccOfSccs::scc_ofSccs.sccOfSccs.SccOf. The code compares factor and
assignment with expression:
// Two rules reach each other if they are in the same SCC.int expressions = sccs.sccOf(expression); // 2boolean factorInIt = sccs.sccOf(factor) == expressions; // trueboolean assignmentInIt = sccs.sccOf(assignment) == expressions; // false// assignment uses expression, but expression does not use assignment.// Two rules reach each other if they are in the same SCC.let expressions = sccs.scc_of(expression); // 2let factor_in_it = sccs.scc_of(factor) == expressions; // truelet assignment_in_it = sccs.scc_of(assignment) == expressions; // false// assignment uses expression, but expression does not use assignment.// Two rules reach each other if they are in the same SCC.const expressions = sccs.sccOf(expression); // 2const factorInIt = sccs.sccOf(factor) === expressions; // trueconst assignmentInIt = sccs.sccOf(assignment) === expressions; // false// assignment uses expression, but expression does not use assignment.// Two rules reach each other if they are in the same SCC.int expressions = sccs.SccOf(expression); // 2bool factorInIt = sccs.SccOf(factor) == expressions; // truebool assignmentInIt = sccs.SccOf(assignment) == expressions; // false// assignment uses expression, but expression does not use assignment.Good to know
Section titled “Good to know”- A node with a self-loop has an edge to itself. It lies on a
cycle but is still an SCC of one node.
Sccs.containsCycleSccs::contains_cycleSccs.containsCycleSccs.ContainsCyclecounts it as an SCC with a cycle. The size of the SCC alone would not show that. - The SCC IDs are an order in which every SCC comes after the SCCs it uses. In the picture after, SCC 2 holds the expressions and SCC 4 holds the statements. SCC 2 comes first, since the statements use the expressions. See Put the nodes in dependency order although the graph has cycles for why this holds and how to use it.
- One question, a faster answer. If you only need to know whether the graph has a cycle at
all,
Graphs.isDaggraphs::is_dagGraphs.isDagGraphs.IsDaganswers it without computing the SCCs.Graphs.isStronglyConnectedgraphs::is_strongly_connectedGraphs.isStronglyConnectedGraphs.IsStronglyConnectedalso works without them: it tells whether every node reaches every other. See Check whether every node reaches every other. With the SCCs at hand,Sccs.isStronglyConnectedSccs::is_strongly_connectedSccs.isStronglyConnectedSccs.IsStronglyConnectedanswers this from them.
API used
Section titled “API used”Components.sccsOf(Graph)components::sccs_ofComponents.sccsOfComponents.SccsOfSccs.sccCount()Sccs::scc_countSccs.sccCountSccs.SccCountSccs.containsCycle(int)Sccs::contains_cycleSccs.containsCycleSccs.ContainsCycleSccs.sccOf(int)Sccs::scc_ofSccs.sccOfSccs.SccOfNodePartition.nodesOf(int)NodePartition::nodes_ofNodePartition.nodesOfNodePartition.NodesOfSccs.isStronglyConnected()Sccs::is_strongly_connectedSccs.isStronglyConnectedSccs.IsStronglyConnectedGraphs.isDag(Graph)graphs::is_dagGraphs.isDagGraphs.IsDagGraphs.isStronglyConnected(Graph)graphs::is_strongly_connectedGraphs.isStronglyConnectedGraphs.IsStronglyConnected