普林斯顿算法-Percolation(渗透问题)

本文参考了:xiewen99 , 周 烨恒, tengyuan93 的博文


底层算法都打包好了,可下载直接用,问题一下子就能应用
在判断block时,用一个数组表示,头尾各增加一个所谓的“隐藏节点”
n=3 n = 3
->

Percolation.java

import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.WeightedQuickUnionUF;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class Percolation {
    private WeightedQuickUnionUF uf;
    private int N;
    private boolean[] sites;
    private int count;

    // create n-by-n grid, with all sites blocked
    public Percolation(int n) {
        this.N = n;
        this.sites = new boolean[N*N+2];
        sites[0] = true;
        sites[N*N+1] = true;
        count = 0;
        uf = new WeightedQuickUnionUF(N*N+2);
    }

    // open site (row, col) if it is not open already
    public void open(int row, int col) {
        if(row < 1 || row > N || col < 1 || col > N)
            throw new IndexOutOfBoundsException("index out of bounds");

        if(sites[(row-1)*N+col])
            return;

        sites[(row-1)*N+col] = true;// open this site
        count++;

        // head & tail
        if(row == 1)
            uf.union(0,(row-1)*N+col);
        if(row == N)
            uf.union((row-1)*N+col,N*N+1);

        // union judge for 4 directions
        if(col != 1 && sites[(row-1)*N+col-1])
            uf.union((row-1)*N+col,(row-1)*N+col-1);
        if(col != N && sites[(row-1)*N+col+1])
            uf.union((row-1)*N+col,(row-1)*N+col+1);
        if(row != 1 && sites[(row-2)*N+col])
            uf.union((row-1)*N+col,(row-2)*N+col);
        if(row != N && sites[row*N+col])
            uf.union((row-1)*N+col,row*N+col);

    }

    public boolean isOpen(int row, int col) {
        if(row < 1 || row > N || col < 1 || col > N)
            throw new IndexOutOfBoundsException("index out of bounds");
        return sites[(row-1)*N+col];
    }

    //connected to an open site in the top row
    public boolean isFull(int row, int col) {
        if(row < 1 || row > N || col < 1 || col > N)
            throw new IndexOutOfBoundsException("index out of bounds");
        return uf.connected((row-1)*N+col,0);
    }

    // number of open sites
    public int numberOfOpenSites() {
        return count;
    }

    // does the system percolate?
    public boolean percolates(){
        return uf.connected(0,N*N+1);
    }

    public static void main(String[] args) {
        try{
            FileInputStream input = new FileInputStream("heart25.txt");
            System.setIn(input);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        int n = StdIn.readInt();
        Percolation percolation = new Percolation(n);
        while (!StdIn.isEmpty()) {
            int row = StdIn.readInt();
            int col = StdIn.readInt();
            percolation.open(row, col);
        }
        System.out.println(percolation.percolates());
        System.out.println(percolation.numberOfOpenSites());
    }
}

PercolationStats.java

import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.StdStats;

import java.util.Scanner;

public class PercolationStats {
    private int sidelength;
    private double mean;
    private double stddev;
    private double conLo;
    private double conHi;
    private double[] experiments;

    // perform trials independent experiments on an n-by-n grid
    public PercolationStats(int n, int trials) {
        if(n <= 0 || trials <= 0)
            throw new IllegalArgumentException("Illegal Argument");
        sidelength = n;
        if(sidelength == 1){
            mean = 1;
            stddev = Double.NaN;
            conLo = Double.NaN;
            conHi = Double.NaN;
        }
        else{
            experiments = new double[trials];
            for(int i=0; i<trials; i++){
                Percolation checkPerco = new Percolation(n);
                int count = 0;
                while(!checkPerco.percolates()) {
                    int row = StdRandom.uniform(n) + 1;
                    int col = StdRandom.uniform(n) + 1;
                    if(!checkPerco.isOpen(row,col)){
                        checkPerco.open(row,col);
                        count++;
                    }
                }
                experiments[i] = (double)count/(n*n);
            }
            mean = StdStats.mean(experiments);
            stddev = StdStats.stddev(experiments);
            conLo = mean - (1.96 * stddev) / Math.sqrt(trials);
            conHi = mean + (1.96 * stddev) / Math.sqrt(trials);
        }
    }

    public double mean() {
        return mean;
    }

    public double stddev() {
        return stddev;
    }

    public double confidenceLo() {
        return conLo;
    }

    public double confidenceHi() {
        return conHi;
    }

    public static void main(String[] args) {
        int n = Integer.parseInt(args[0]);
        int trails = Integer.parseInt(args[1]);
        PercolationStats per = new PercolationStats(n,trails);
        System.out.println("mean:  " + per.mean());
        System.out.println("stddev:  " + per.stddev());
        System.out.println("confidence Low:  " 
                            + per.confidenceLo());
        System.out.println("confidence High:  " 
                            + per.confidenceHi());
    }
}

顺带一提这个课的Judge机制很棒

  • 3
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值