Coursera Algorithm class programming assignment 1——Percolation

public class Percolation {

	private int[][] iGrid;
	private int iN;
	private WeightedQuickUnionUF uf;
	
	public Percolation(int N){
		// create N-by-N grid, with all sites blocked
		if(N <= 0){
			throw new IllegalArgumentException();
		}
		iGrid = new int[N][N];
		uf = new WeightedQuickUnionUF(N*N+2);
		for(int i=0; i<N; i++){
			uf.union(0, i+1);
			uf.union(N*N+1, N*N-i);
		}
		
		iN = N;
	}
	   public void open(int i, int j) {
		   // open site (row i, column j) if it is not already
		   if(i <= 0 || j <= 0 || i > iN || j > iN){
			   throw new IndexOutOfBoundsException();
		   }
		   if(isOpen(i, j) == false){
			   iGrid[i-1][j-1] = 1;
		   }
	   }
	   public boolean isOpen(int i, int j) {
		   // is site (row i, column j) open?
		   if(i <= 0 || j <= 0 || i > iN || j > iN){
			   throw new IndexOutOfBoundsException();
		   }
		   if(iGrid[i-1][j-1] == 0){
			   return false;
		   }
		   else{
			   return true;
		   }
	   }
	   public boolean isFull(int i, int j){
		   // is site (row i, column j) full?
		   if(i <= 0 || j <= 0 || i > iN || j > iN){
			   throw new IndexOutOfBoundsException();
		   }
		   for(int m=1; m<=iN; m++){
			   for(int n=1; n<=iN; n++){
				   if(isOpen(m, n)){
					   if(n-1 > 0){
						   if(isOpen(m, n-1)){
							   uf.union(iN*(m-1)+n-1+1, iN*(m-1)+n-2+1);
						   }
					   }
					   if(n+1 <= iN){
						   if(isOpen(m, n+1)){
							   uf.union(iN*(m-1)+n-1+1, iN*(m-1)+n+1);
						   }
					   }
					   if(m-1 > 0){
						   if(isOpen(m-1, n)){
							   uf.union(iN*(m-2)+n-1+1, iN*(m-1)+n-1+1);
						   }
					   }
					   if(m+1 <= iN){
						   if(isOpen(m+1, n)){
							   uf.union(iN*(m-1)+n-1+1, iN*(m)+n-1+1);
						   }
					   }
				   }
			   }
		   }
		   if(uf.connected(iN*(i-1)+j-1+1, 0)){
			   return true;
		   }
		   else{
			   return false;
		   }
		   
	   }
	   public boolean percolates(){
		   // does the system percolate?
		   isFull(3, 1);
		   //uf.union(0, iN*iN+1);
		   if(uf.connected(0, iN*iN+1)){
			   return true;
		   }
		   else{
			   return false;
		   }
		   
	   }
	   public static void main(String[] args){
		   // test client, optional
		   Percolation pcl = new Percolation(4);
		   pcl.open(1, 1);
		   pcl.open(1, 2);
		   pcl.open(2, 2);
		   pcl.open(2, 3);
		   pcl.open(3, 3);
		   pcl.open(3, 4);
		   pcl.open(4, 3);
		   //boolean a = pcl.isFull(3, 1);
		   //StdOut.println(a);
		   boolean b = pcl.percolates();
		   StdOut.println(b);
	   }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值