我在使用加权快速UnionFind循环处理此特定程序时遇到了麻烦。谁能弄清楚为什么会出现此错误?我怎样才能解决这个问题?我试图在此处更改参数,但该错误仍未解决。
是在Percolation()中还是在主参数本身中?请赐教,因为有这种编程问题已经有一段时间了。
import edu.princeton.cs.algs4.WeightedQuickUnionUF;
import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
import java.lang.*;
public class Percolation {
int n;
private boolean[][] grid;
private WeightedQuickUnionUF uf;
int openSites;
// creates n-by-n grid, with all sites initially blocked
public Percolation(int n) {
this.n = n;
this.uf = new WeightedQuickUnionUF(n * n + 2);
this.grid = new boolean[n][n];
for (int row = 0; row <= n; row++){
for (int col = 0; col <= n; col++)
{
grid[row][col] = false;
}
}
for (int i = 0; i <= n; i++){
uf.union (n * n, i);
}
this.openSites = 0;
}
// opens the site (row, col) if it is not open already
public void open(int row, int col)
{
if ((row < 0 || col < 0) && (row >= n || col >= n)) {
throw new IllegalArgumentException("Value must be above 0!");
}
if(!(this.grid[row][col])){
this.grid[row][col] = true;
openSites++;
}
if (isOpen(row - 1, col)) { // open left
uf.union(convert2D(row, col), convert2D(row - 1, col));
}
if (isOpen(row + 1, col)) { // open right
uf.union(convert2D(row, col), convert2D(row + 1, col));
}
if (isOpen(row, col + 1)) { // open down
uf.union(convert2D(row, col), convert2D(row, col + 1));
}
if (isOpen(row, col - 1)) { // open up
uf.union(convert2D(row, col), convert2D(row, col - 1));
}
}
// is the site (row, col) open?
public boolean isOpen(int row, int col)
{
if ((row < 0 || col < 0) && (row >= n || col >= n)) {
throw new IllegalArgumentException("Value must be above 0!");
}
return grid[row][col];
}
// is the site (row, col) full?
public boolean isFull(int row, int col)
{ ;
if ((row < 0 || col < 0) && (row >= n || col >= n)) {
throw new IllegalArgumentException("Value must be above 0!");
}
if (isOpen(row, col)){
if (uf.find(row + col * n) == uf.find(n * n)) return true;
}
return uf.find(n * n) == uf.find(convert2D(row, col) - 1);
}
// returns the number of open sites
public int numberOfOpenSites()
{
return openSites;
}
// turns [row][cool] coordinates to uf values
private int convert2D(int row, int col){
return (n * row) + col + 1;
}
// does the system percolate?
public boolean percolates()
{ return uf.find(n * n) == uf.find (n * n + 1); }
// test client (optional)
public static void main(String[] args){
int x = Integer.parseInt(args[0]);
Percolation perc = new Percolation(x);
int testTrials = 1;
int argsCount = args.length;
for (int i = 1; argsCount >= 2; i += 2)
{
int row = Integer.parseInt(args[i]);
int col = Integer.parseInt(args[i + 1]);
perc.open(row, col);
if (perc.percolates()){
StdOut.println("The system percolates.");
}
argsCount -= 2;
}
if (!perc.percolates()){
StdOut.println("The system does not percolate.");
}
}
}