public List <Edge> GetKruskalsMST(Graph graph) { graph.Edges.Sort(new EdgeComparator()); DisjointSet disjointSet = new DisjointSet(); // Create as many disjoint sets as the total vertices foreach (KeyValuePair <long, Vertex> vertexPair in graph.Verticies) { disjointSet.MakeSet(vertexPair.Value.Id); } List <Edge> resultEdges = new List <Edge>(); foreach (Edge edge in graph.Edges) { // Get the sets of two vertices of the edge long root1 = disjointSet.FindSet(edge.Vertex1.Id); long root2 = disjointSet.FindSet(edge.Vertex2.Id); // Check if the vertices are in same set or different set // If verties are in same set then ignore the edge if (root1 == root2) { continue; } else { // If vertices are in different set then add the edge to result and union these two sets into one resultEdges.Add(edge); disjointSet.Union(edge.Vertex1.Id, edge.Vertex2.Id); } } return(resultEdges); }
public static void DisjointSetTest() { DisjointSet ds = new DisjointSet(); ds.MakeSet(1); ds.MakeSet(2); ds.MakeSet(3); ds.MakeSet(4); ds.MakeSet(5); ds.MakeSet(6); ds.MakeSet(7); ds.Union(1, 2); ds.Union(2, 3); ds.Union(4, 5); ds.Union(6, 7); ds.Union(5, 6); ds.Union(3, 7); Console.WriteLine("DisjoinSet Demo :"); Console.WriteLine(ds.FindSet(1)); Console.WriteLine(ds.FindSet(2)); Console.WriteLine(ds.FindSet(3)); Console.WriteLine(ds.FindSet(4)); Console.WriteLine(ds.FindSet(5)); Console.WriteLine(ds.FindSet(6)); Console.WriteLine(ds.FindSet(7)); }
//======================================================================================================================= public bool HasCycleUsingDisjointSets(Graph graph) { DisjointSet disjointSet = new DisjointSet(); foreach (KeyValuePair <long, Vertex> vertexPair in graph.Verticies) { disjointSet.MakeSet(vertexPair.Key); } foreach (Edge edge in graph.Edges) { long parent1 = disjointSet.FindSet(edge.Vertex1.Id); long parent2 = disjointSet.FindSet(edge.Vertex2.Id); if (parent1 == parent2) { return(true); } disjointSet.Union(edge.Vertex1.Id, edge.Vertex2.Id); } return(false); }