Example #1
0
        public List <Edge> KruskalMST()
        {
            List <Edge> minimumSpanningTreeEdges = new List <Edge>();
            UnionFindDs unionFindDs = new UnionFindDs(this.V);

            //Sort all edges by their weight
            this.Edges.Sort();

            foreach (var edge in this.Edges)
            {
                //If tree is built, all vertex are connected, then no need to check more
                if (minimumSpanningTreeEdges.Count >= this.V - 1)
                {
                    break;
                }

                int edgeFromEndPointGroup = unionFindDs.Find(edge.From);
                int edgeToEndPointGroup   = unionFindDs.Find(edge.To);

                if (edgeFromEndPointGroup != edgeToEndPointGroup)
                {
                    minimumSpanningTreeEdges.Add(edge);
                    unionFindDs.Union(edge.From, edge.To);
                }
            }

            return(minimumSpanningTreeEdges);
        }
Example #2
0
        public bool IsCyclicUsingUnionFind()
        {
            UnionFindDs unionFind = new UnionFindDs(this.V);

            for (int fromVertex = 0; fromVertex < this.V; fromVertex++)
            {
                foreach (var adjacentVertex in adj[fromVertex])
                {
                    //for each edge , we are running it
                    int x = unionFind.Find(fromVertex);
                    int y = unionFind.Find(adjacentVertex.Id);
                    if (x == y)                     // in same group (only if both are not -1)
                    {
                        return(true);               //cycle found
                    }
                    else
                    {
                        unionFind.Union(fromVertex, adjacentVertex.Id);
                    }
                }
            }
            return(false);
        }