5.1 Find the components of a graph read as undirected
You get the weakly connected components of a graph: the groups of nodes that paths connect when the direction of the edges does not matter.
Problem
Section titled “Problem”You want to know which nodes of a graph are connected at all, whatever the direction of the edges, or just whether everything is connected. Reading the edges without their direction is called the undirected reading. In this reading, a group of nodes that are connected by paths, as large as it can be, is called a component. No path connects nodes in different components. You need this to find:
- modules of a codebase that no reference connects, and that could be split off;
- sub-problems that do not depend on each other, and can be solved separately;
- networks with no link between them.
Example
Section titled “Example”The example graph calls models the calls between the methods of a small program. It has an edge
from each method to each method it calls. The array names holds the names of the methods. main
and run call into every area of the program. The picture before shows the calls they make as
dashed edges. Without these calls, which methods are still connected by calls?
- Call left out
- Component
The picture after shows the five components that remain, each in a frame.
Solution
Section titled “Solution”Build the graph without the calls of main and run, then find its components:
// Leave out the calls of main and run, which call into every area of the program.var builder = new GraphBuilder();builder.addNodes(calls.nodeCount());calls.forEachEdge((caller, callee, edge) -> { if (caller != main && caller != run) { builder.addEdge(caller, callee); }});Graph rest = builder.build();// Leave out the calls of main and run, which call into every area of the program.let mut builder = GraphBuilder::new();builder.add_nodes(calls.node_count());calls.for_each_edge(|caller, callee, _edge| { if caller != main && caller != run { builder.add_edge(caller, callee); }});let rest = builder.build();// Leave out the calls of main and run, which call into every area of the program.const builder = new GraphBuilder();builder.addNodes(calls.nodeCount);calls.forEachEdge((caller, callee) => { if (caller !== main && caller !== run) { builder.addEdge(caller, callee); }});const rest = builder.build();// Leave out the calls of main and run, which call into every area of the program.var builder = new GraphBuilder();builder.AddNodes(calls.NodeCount);calls.ForEachEdge((caller, callee, _) =>{ if (caller != main && caller != run) { builder.AddEdge(caller, callee); }});Graph rest = builder.Build();NodePartition components = Components.wccsOf(rest);int componentCount = components.groupCount(); // 5List<List<String>> byName = new ArrayList<>();for (int component = 0; component < componentCount; component++) { byName.add( components.nodesOf(component).intStream().mapToObj(m -> names[m]).toList());}// byName: [[main], [parseArgs], [run], [load, parse, read],// [save, show, format, write]]
boolean callsConnected = Graphs.isWeaklyConnected(calls); // trueboolean restConnected = Graphs.isWeaklyConnected(rest); // falselet components = components::wccs_of(&rest);let component_count = components.group_count(); // 5let by_name: Vec<Vec<&str>> = (0..component_count) .map(|component| { components .nodes_of(component) .iter() .map(|&m| names[m as usize]) .collect() }) .collect();// by_name: [["main"], ["parseArgs"], ["run"], ["load", "parse", "read"],// ["save", "show", "format", "write"]]
let calls_connected = graphs::is_weakly_connected(&calls); // truelet rest_connected = graphs::is_weakly_connected(&rest); // falseconst components = Components.wccsOf(rest);const componentCount = components.groupCount; // 5const byName: string[][] = [];for (let component = 0; component < componentCount; component++) { byName.push(Array.from(components.nodesOf(component), (m) => names[m]));}// byName: [[main], [parseArgs], [run], [load, parse, read],// [save, show, format, write]]
const callsConnected = Graphs.isWeaklyConnected(calls); // trueconst restConnected = Graphs.isWeaklyConnected(rest); // falseNodePartition components = Components.WccsOf(rest);int componentCount = components.GroupCount; // 5List<List<string>> byName = [];for (int component = 0; component < componentCount; component++){ byName.Add([.. components.NodesOf(component).Select(m => names[m])]);}// byName: [[main], [parseArgs], [run], [load, parse, read],// [save, show, format, write]]
bool callsConnected = Graphs.IsWeaklyConnected(calls); // truebool restConnected = Graphs.IsWeaklyConnected(rest); // falseComponents.wccsOfcomponents::wccs_ofComponents.wccsOfComponents.WccsOf returns a NodePartitionNodePartitionNodePartitionNodePartition with five groups. One
group holds load, parse and read. One group holds save, show, format and write. Each
of main, parseArgs and run is a group of its own. All the calls together are one component.
The calls without those of main and run are not.
Good to know
Section titled “Good to know”- A partition. The result is a partition of the nodes,
like the strongly connected components. Every
node is in exactly one component.
IndexPartition.groupCountIndexPartition::group_countIndexPartition.groupCountIndexPartition.GroupCountcounts the components, andNodePartition.nodesOfNodePartition::nodes_ofNodePartition.nodesOfNodePartition.NodesOflists the nodes of each in ascending order. The group IDs are in the order of the smallest nodes of the components. Component 0 holds node 0, component 1 holds the smallest node that component 0 does not hold, and so on. Here each group ID happens to equal the smallest node of its component. In general it does not. - Weakly or not? For a directed graph, these components are called weakly connected. The
strongly connected ones follow the direction of the edges. See
Find the groups of nodes that reach each other. For a
graph that stands for an undirected one,
Components.ccsOfcomponents::ccs_ofComponents.ccsOfComponents.CcsOfreturns the same result under the name of connected components. The two names let the code say which reading it means. - Connected or not.
Graphs.isWeaklyConnectedgraphs::is_weakly_connectedGraphs.isWeaklyConnectedGraphs.IsWeaklyConnectedbuilds no partition and stops as soon as all nodes are connected. The empty graph and a graph of a single node are weakly connected. - Leaving out nodes. To leave out nodes instead of edges, take the subgraph of the nodes you keep. See Take the subgraph of some nodes.
API used
Section titled “API used”Components.wccsOf(Graph)components::wccs_ofComponents.wccsOfComponents.WccsOfComponents.ccsOf(Graph)components::ccs_ofComponents.ccsOfComponents.CcsOfGraphs.isWeaklyConnected(Graph)graphs::is_weakly_connectedGraphs.isWeaklyConnectedGraphs.IsWeaklyConnectedIndexPartition.groupCount()IndexPartition::group_countIndexPartition.groupCountIndexPartition.GroupCountNodePartition.nodesOf(int)NodePartition::nodes_ofNodePartition.nodesOfNodePartition.NodesOfGraphBuilder()GraphBuilder::newnew GraphBuildernew GraphBuilderGraphBuilder.addNodes(int)GraphBuilder::add_nodesGraphBuilder.addNodesGraphBuilder.AddNodesGraphBuilder.addEdge(int, int)GraphBuilder::add_edgeGraphBuilder.addEdgeGraphBuilder.AddEdgeGraphBuilder.build()GraphBuilder::buildGraphBuilder.buildGraphBuilder.BuildGraph.forEachEdge(EdgeConsumer)Graph::for_each_edgeGraph.forEachEdgeGraph.ForEachEdge