Coursera Algorithm class programming assignment 1——Percolation

来源:互联网 发布:淘宝比较好的模型店 编辑:程序博客网 时间:2024/05/17 20:11
public class Percolation {private int[][] iGrid;private int iN;private WeightedQuickUnionUF uf;public Percolation(int N){// create N-by-N grid, with all sites blockedif(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);   }}

0 0
原创粉丝点击