Beispiel #1
0
        //https://leetcode.com/problems/graph-valid-tree/

        /*
         * Approach
         *  Use Union Find Algorith preferably with weighed quick-union
         *
         *
         *
         *
         *
         *
         *
         */

        public bool ValidTree(int n, int[][] edges)
        {
            WeightedQuickUnionFind qfind = new WeightedQuickUnionFind(n);
            int m = edges.GetLength(0);

            for (int i = 0; i < m; i++)
            {
                int p = edges[i][0];
                int q = edges[i][1];

                //p & q in the same set then there is a cycle
                if (qfind.Find(p) == qfind.Find(q))
                {
                    return(false);
                }

                qfind.Union(p, q);
            }

            if (qfind.Count() != 1)
            {
                return(false);
            }

            return(true);
        }
Beispiel #2
0
        public int RemoveStonesUnionFind(int[][] stones)
        {
            int L = stones.GetLength(0);
            WeightedQuickUnionFind uf = new WeightedQuickUnionFind(L);

            for (int i = 0; i < L; i++)
            {
                for (int j = i + 1; j < L; j++)
                {
                    if (stones[i][0] == stones[j][0] || stones[i][1] == stones[j][1])
                    {
                        uf.Union(i, j);
                    }
                }
            }

            int count = 0;

            int[] componentSize = uf.Size();     //calculate the individual component sizes
            for (int i = 0; i < componentSize.Length; i++)
            {
                count += componentSize[i] > 1 ? componentSize[i] - 1 : 0;
            }
            return(count);
        }