Programming Assignment 1: Percolation

Source: Internet
Author: User

Problem description can see: http://coursera.cs.princeton.edu/algs4/assignments/percolation.html

Javadoc for quickfinduf: http://algs4.cs.princeton.edu/15uf/QuickFindUF.java.html

Javadoc: http://algs4.cs.princeton.edu/15uf/WeightedQuickUnionUF.java.html for weightedquickunionuf

Postscript: (referenced in http://blog.csdn.net/revilwang/article/details/10823467)

There is actually a problem with this model. The Forum on algorithm courses is very popular. The problem is as follows:

The introduction of virtual top-level areas and virtual bottom-layer areas may cause model penetration.

As shown in the picture on the right, because all the bottom-layer areas are connected to the virtual bottom-layer areas, once the areas penetrate, the areas connected to other bottom-layer open areas are also displayed as full. The actual situation is shown in the left figure. This problem is called backwash. I translate it into "reflux ". It is difficult to avoid this problem by introducing the virtual underlying area. There are two ways to improve the discussion results:

1. The virtual bottom layer is not used, and only the top layer is retained. when determining whether to penetrate, the virtual top layer and a for loop are used to determine.

2. Retain the virtual underlying area, add a model that does not use the virtual underlying layer, and combine the two models to determine whether or not to penetrate. This ensures efficiency by wasting some memory.

Backwash results in an error in the percolation. Java public void isfull (int I, Int J) method during the test. This can be seen from the above two figures. (The solution is implemented through the above two methods)

The following two pieces of code are fromHttp://www.cnblogs.com/tiny656/p/3820653.htmlI copied it because I did not take into account the backwash situation, so there are some errors, so I won't stick it up.

Percolation. Java

public class Percolation {        private boolean[] matrix;    private int row, col;    private WeightedQuickUnionUF wquUF;    private WeightedQuickUnionUF wquUFTop;    private boolean alreadyPercolates;        public Percolation(int N) {        if (N < 1) throw new IllegalArgumentException("Illeagal Argument");        wquUF = new WeightedQuickUnionUF(N*N+2);        wquUFTop = new WeightedQuickUnionUF(N*N+1);        alreadyPercolates = false;        row = N;        col = N;        matrix = new boolean[N*N+1];    }        private void validate(int i, int j) {        if (i < 1 || i > row)             throw new IndexOutOfBoundsException("row index i out of bounds");        if (j < 1 || j > col)             throw new IndexOutOfBoundsException("col index j out of bounds");            }        public void open(int i, int j) {        validate(i, j);        int curIdx = (i-1)*col + j;         matrix[curIdx] = true;        if (i == 1) {            wquUF.union(curIdx, 0);            wquUFTop.union(curIdx, 0);        }        if (i == row) {            wquUF.union(curIdx, row*col+1);        }                int[] dx = {1, -1, 0, 0};        int[] dy = {0, 0, 1, -1};        for (int dir = 0; dir < 4; dir++) {            int posX = i + dx[dir];            int posY = j + dy[dir];            if (posX <= row && posX >= 1                     && posY <= row && posY >= 1                     && isOpen(posX, posY)) {                wquUF.union(curIdx, (posX-1)*col+posY);                wquUFTop.union(curIdx, (posX-1)*col+posY);            }        }    }        public boolean isOpen(int i, int j) {        validate(i, j);        return matrix[(i-1)*col + j];    }        public boolean isFull(int i, int j) {        validate(i, j);        int curIdx = (i-1)*col+j;        if (wquUFTop.find(curIdx) == wquUFTop.find(0)) return true;        return false;    }        public boolean percolates() {        if (alreadyPercolates) return true;        if (wquUF.find(0) == wquUF.find(row*col+1)) {            alreadyPercolates = true;            return true;        }         return false;    }        public static void main(String[] args) {        Percolation perc = new Percolation(2);        perc.open(1, 1);        perc.open(1, 2);        perc.open(2, 1);        System.out.println(perc.percolates());    }    }

 

Percolationstats. Java

public class PercolationStats {    private double[] x;    private int expTime;   public PercolationStats(int N, int T) {    // perform T independent experiments on an N-by-N grid          if (N <= 0 || T <= 0)           throw new IllegalArgumentException("Illeagal Argument");       x = new double[T+1];       expTime = T;       for (int i = 1; i <= T; i++) {           Percolation perc = new Percolation(N);           while (true) {                          int posX, posY;               do {                   posX = StdRandom.uniform(N) + 1;                   posY = StdRandom.uniform(N) + 1;               } while(perc.isOpen(posX, posY));               perc.open(posX, posY);               x[i] += 1;                  if (perc.percolates())                          break;               }           x[i] = x[i]/(double) (N * N);       }   }   public double mean() {                     // sample mean of percolation threshold          double u = 0.0;       for (int i = 1; i <= expTime; i++) {                  u += x[i];       }       return u / (double)expTime;   }   public double stddev() {                   // sample standard deviation of percolation threshold          double q = 0.0;       double u = mean();       for (int i = 1; i <= expTime; i++) {                  q += (x[i]-u)*(x[i]-u);       }       return Math.sqrt(q / (double)(expTime - 1));   }   public double confidenceLo() {            // low  endpoint of 95% confidence interval          double mu = mean();       double sigma = stddev();       return mu - 1.96*sigma / Math.sqrt(expTime);   }   public double confidenceHi() {           // high endpoint of 95% confidence interval          double mu = mean();       double sigma = stddev();       return mu + 1.96*sigma / Math.sqrt(expTime);       }   public static void main(String[] args) {   // test client (described below)          int N = Integer.parseInt(args[0]);       int T = Integer.parseInt(args[1]);       PercolationStats percStats = new PercolationStats(N, T);       StdOut.printf("mean = %f\n", percStats.mean());       StdOut.printf("stddev = %f\n", percStats.stddev());       StdOut.printf("95%% confidence interval = %f, %f\n",                       percStats.confidenceLo(), percStats.confidenceHi());   }}

Programming Assignment 1: Percolation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.