Beispiel #1
0
        public Percolation(int n)
        {
            this.n          = n;
            this.openMatrix = new bool[n][];
            uf        = new WeightedQuickUnionPathCompressionUF(n * n + 2);
            this.top  = n * n;
            this.last = n * n + 1;

            for (int i = 1; i <= n; i++)
            {
                uf.Union(this.top, this.toOneDimension(1, i));
                uf.Union(this.last, this.toOneDimension(n, i));
            }
        }// create n-by-n grid, with all sites blocked
Beispiel #2
0
        public static void Main(string[] args)
        {
            int N = StdIn.ReadInt();

            WeightedQuickUnionPathCompressionUF uf = new WeightedQuickUnionPathCompressionUF(N);

            // read in a sequence of pairs of integers (each in the range 0 to N-1),
            // calling find() for each pair: If the members of the pair are not already
            // call union() and print the pair.
            while (!StdIn.IsEmpty())
            {
                int p = StdIn.ReadInt();
                int q = StdIn.ReadInt();

                if (uf.Connected(p, q))
                {
                    continue;
                }
                uf.Union(p, q);

                Console.WriteLine(p + " " + q);
            }

            Console.WriteLine(uf.Count + " components");
        }
Beispiel #3
0
        }// create n-by-n grid, with all sites blocked

        public void open(int row, int col)
        {
            if (!isOpen(row, col))
            {
                setMatrixCell(row, col);
            }

            foreach (int[] direction in directions)
            {
                int i = row + direction[0];
                int j = col + direction[1];

                if (isValid(i, j))
                {
                    if (isOpen(i, j))
                    {
                        setMatrixCell(row, col);
                        uf.Union(this.toOneDimension(row, col), this.toOneDimension(i, j));
                    }
                }
            }
        }// open site (row, col) if it is not open already