static void SetComponentAllVerts(GraphVertex[] graph, ComponentIndex comp1, ComponentIndex comp2) { foreach (int j in comp2.verts) { graph[j].componentIndex = comp1; comp1.verts.Add(j); } comp1.index = Math.Min(comp1.index, comp2.index); }
static void MergeComponents(GraphVertex[] graph, ComponentIndex comp1, ComponentIndex comp2) { if (comp1.verts.Count > comp2.verts.Count) { SetComponentAllVerts(graph, comp1, comp2); } else { SetComponentAllVerts(graph, comp2, comp1); } }
static void dfs(GraphVertex[] graph, int i, ref bool[] visited, ref ComponentIndex ci) { visited[i] = true; if (graph[i] == null) { graph[i] = new GraphVertex(); } graph[i].componentIndex = ci; graph[i].componentIndex.verts.Add(i); foreach (int j in graph[i].neighbours) { if (!visited[j]) { dfs(graph, j, ref visited, ref ci); } } }
static int Calculate(GraphVertex[] graph) { bool[] visited = new bool[graph.Length + 1]; int result = 0; for (int i = 1; i < graph.Length; i++) { if (visited[i] == false) { ComponentIndex ci = new ComponentIndex() { index = result }; dfs(graph, i, ref visited, ref ci); result++; } } return(result - 1); }