/// <summary> /// find component /// </summary> /// <param name="graph"></param> /// <returns></returns> public static List <HashSet <int> > ConnectedComponent(this Graph.Graph graph) { if (graph == null) { return(new List <HashSet <int> >()); } // List <HashSet <int> > lists = new List <HashSet <int> >(); for (int i = 0; i < graph.V; i++) { HashSet <int> set = new HashSet <int>(); set.Add(i); lists.Add(set); } List <Tuple <int, int> > tuples = new List <Tuple <int, int> >(); for (int i = 0; i < graph.V; i++) { foreach (int j in graph.Adj(i)) { bool found = false; foreach (var t in tuples) { if ((t.Item1 == i && t.Item2 == j) || (t.Item1 == j && t.Item2 == i)) { found = true; break; } } if (!found) { tuples.Add(new Tuple <int, int>(i, j)); } } } foreach (var tuple in tuples) { HashSet <int> set1 = null; HashSet <int> set2 = null; foreach (var list in lists) { if (list.Contains(tuple.Item1)) { set1 = list; } if (list.Contains(tuple.Item2)) { set2 = list; } if (set1 != null && set2 != null) { break; } } if (set1 == set2) { continue; } lists.Remove(set1); lists.Remove(set2); set1.UnionWith(set2); lists.Add(set1); } return(lists); }