Programming Assignment 1: Percolation

问题描述可以详见:http://coursera.cs.princeton.edu/algs4/assignments/percolation.html

关于QuickFindUF的javadoc:http://algs4.cs.princeton.edu/15uf/QuickFindUF.java.html

关于WeightedQuickUnionUF的javadoc:http://algs4.cs.princeton.edu/15uf/WeightedQuickUnionUF.java.html

附言:(引用于http://blog.csdn.net/revilwang/article/details/10823467

关于这个模型,其实存在一个问题,在算法课程的论坛上,讨论的热度很高。问题是这样的:

由于引入虚拟的顶层区域和虚拟的底层区域,那么当模型渗透的时候,可能会出现下图的情况

如右边图所示,由于所有的底层区域都和虚拟底层区域相连,所以一旦当区域渗透,则和其他的底层开启区域相连的区域也显示为区域满状态。而实际的情况应该是按照左图所示。这个问题称为 backwash,个人把这个翻译成“回流”。引入虚拟底层区域,很难避免这个问题。讨论的结果,有两种方式可以改进:

1. 不使用虚拟底层区域,只保留顶层,判断是否渗透的时候用虚拟顶层和一个for循环来判断。

2. 保留虚拟底层区域,另外加一个不使用虚拟底层的模型,将两个模型结合在一起来判断是否渗透,通过浪费一些内存来保证效率。

backwash的情况导致Percolation.java在测试时public void isfull(int i, int j) 方法出现错误,这一点从上面两张图也可以明显的看出来。(而解决的办法通过上面两种方法实现)

下面两段代码是从http://www.cnblogs.com/tiny656/p/3820653.html 复制来的,因为自己写的没有考虑到backwash的情况,所以有一些错误,就不挂上来误人子弟了。

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());

   }
}
时间: 2024-10-11 03:27:41

Programming Assignment 1: Percolation的相关文章

AlgorithmsI Programming Assignment 1: Percolation

3种版本的答案,第一种使用virtual top and bottom site, 但有backwash的问题,解决这个问题有两种方法: 1. 使用2个WQUUF, 但会增加memory. One for checking if the system percolates(include virtual top and bottom), and the other to check if a given cell is full(only include virtual top). 而且要注意,

Coursera Algorithms Programming Assignment 1: Percolation

题目来源http://coursera.cs.princeton.edu/algs4/assignments/percolation.html 作业分为两部分:建立模型和仿真实验. 最关键的部分就是建立模型对象.模型对象要求如下: The model.  We model a percolation system using an n-by-n grid of sites. Each site is either open or blocked. A full site is an open s

Algorithm Part I:Programming Assignment(2)

问题描述: Programming Assignment 2: Randomized Queues and Deques Write a generic data type for a deque and a randomized queue. The goal of this assignment is to implement elementary data structures using arrays and linked lists, and to introduce you to g

Programming Assignment 3 : Pattern Recognition

这周的这个问题是在给定一系列的点中寻找多点共线的模式. 计算机视觉重要的两个部分:特征检测(Feature Dectection)和模式识别(Pattern Recognition).特征检测提取出图片的重要特征,模式识别发掘出这些特征中的模式.这里探究的点共线的问题在现实生活中也有很多应用,比如统计数据分析. Problem. 从二维平面上的N个互不相同的点中,绘制出每个(最多)连接的4个或4个以上点集合的线段. Point data type. 给定的Point类型的API public c

Programming Assignment 4: 8 Puzzle

The Problem. 求解8数码问题.用最少的移动次数能使8数码还原. Best-first search.使用A*算法来解决,我们定义一个Seach Node,它是当前搜索局面的一种状态,记录了从初始到达当前状态的移动次数和上一个状态.初始化时候,当前状态移动次数为0,上一个状态为null,将其放入优先级队列,通过不断的从优先级队列中取出Seach Node去扩展下一级的状态,直到找到目标状态.对于优先级队列中优先级的定义我们可以采用:Hamming priority function 和

Algorithm Part I:Programming Assignment(3)

问题描述: Programming Assignment 3: Pattern Recognition Write a program to recognize line patterns in a given set of points. Computer vision involves analyzing patterns in visual images and reconstructing the real-world objects that produced them. The pr

Programming Assignment 1: WordNet

题目地址:http://coursera.cs.princeton.edu/algs4/assignments/wordnet.html 1. 题目阅读 WordNet定义 WordNet是指一个包含唯一根的有向无环图,图中每一组词表示同一集合,每一条边v→w表示w是v的上位词.和树不同的地方是,每一个子节点可以有许多父节点. 输入格式 同义词表 文件中每行包含一次同义名词.首先是序号:然后是词,用空格分开.若为词组,则使用下划线连接词组.最后是同义名词的注释 36,AND_circuit AN

Algorithms: Design and Analysis, Part 1 - Programming Assignment #1

自我总结: 1.编程的思维不够,虽然分析有哪些需要的函数,但是不能比较好的汇总整合 2.写代码能力,容易挫败感,经常有bug,很烦心,耐心不够好 题目: In this programming assignment you will implement one or more of the integer multiplication algorithms described in lecture. To get the most out of this assignment, your pro

CMPT 459.1-19. Programming Assignment

---title: "CMPT 459.1-19. Programming Assignment 1"subtitle: "FIFA 19Players"author: "Name - Student ID"output: html_notebook---### IntroductionThe data has detailed attributes for every player registered inthe latest edition