( graph: Graph<N, E, "undirected"> | MutableGraph<N, E, "undirected"> )
| 2145 | * @category algorithms |
| 2146 | */ |
| 2147 | export const connectedComponents = <N, E>( |
| 2148 | graph: Graph<N, E, "undirected"> | MutableGraph<N, E, "undirected"> |
| 2149 | ): Array<Array<NodeIndex>> => { |
| 2150 | const visited = new Set<NodeIndex>() |
| 2151 | const components: Array<Array<NodeIndex>> = [] |
| 2152 | for (const startNode of graph.nodes.keys()) { |
| 2153 | if (!visited.has(startNode)) { |
| 2154 | // DFS to find all nodes in this component |
| 2155 | const component: Array<NodeIndex> = [] |
| 2156 | const stack: Array<NodeIndex> = [startNode] |
| 2157 | |
| 2158 | while (stack.length > 0) { |
| 2159 | const current = stack.pop()! |
| 2160 | if (!visited.has(current)) { |
| 2161 | visited.add(current) |
| 2162 | component.push(current) |
| 2163 | |
| 2164 | // Add all unvisited neighbors to stack |
| 2165 | const nodeNeighbors = getUndirectedNeighbors(graph, current) |
| 2166 | for (const neighbor of nodeNeighbors) { |
| 2167 | if (!visited.has(neighbor)) { |
| 2168 | stack.push(neighbor) |
| 2169 | } |
| 2170 | } |
| 2171 | } |
| 2172 | } |
| 2173 | |
| 2174 | components.push(component) |
| 2175 | } |
| 2176 | } |
| 2177 | |
| 2178 | return components |
| 2179 | } |
| 2180 | |
| 2181 | /** |
| 2182 | * Find strongly connected components in a directed graph using Kosaraju's algorithm. |
nothing calls this directly
no test coverage detected