我有分支和边界的实现我在这个函数中遇到错误有优先级队列将进一步使用它IllegalArgumentException
//这是我收到此错误的那一行
PriorityQueue<Node> pq = new PriorityQueue<>(0, comp);
import java.util.Comparator;
import java.util.PriorityQueue;
public class Node {
private int N = 3;
Node parent;
int[][] mat = new int[N][N];
int x, y;
int cost;
int level;
public void printMatrix(int[][] mat) {
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[i].length; j++) {
System.out.print(mat[i][j]);
}
System.out.println();
}
}
public void newNode(int[][] mat, int x, int y, int newX, int newY, int level, Node parent) {
Node node = new Node();
node.parent = parent;
node.mat = mat;
node.mat[x][y] = node.mat[newX][newY];
node.cost = Integer.MAX_VALUE;
node.level = level;
node.x = newX;
node.y = newY;
}
int[] row = {1, 0, -1, 0};
int[] col = {0, -1, 0, 1};
public int calculateCost(int[][] initial, int[][] fin) {
int count = 0;
for (int i = 0; i < fin.length; i++) {
for (int j = 0; j < fin.length; j++) {
if(initial[i][j] != fin[i][j])
count++;
}
}
return count;
}
public int isSafe(int x, int y) {
if ((x >= 0 && x < N) && (y >= 0 && y < N))
return 1;
return 0;
}
public void printPath(Node root) {
if(root == null)
return;
printPath(root.parent);
printMatrix(root.mat);
System.out.println();
}
** //这里我在这个函数中遇到错误,有优先级队列将进一步使用它获取IllegalArgumentException **
public void solve(int[][] initial, int x, int y, int[][] fin) {
Comparator<Node> comp = new Comparator<Node>() {
@Override
public int compare(Node lhs, Node rhs) {
if((lhs.cost + lhs.level) > (rhs.cost + rhs.level))
return 1;
return 0;
}
};
//here is that line on which im getting this error
PriorityQueue<Node> pq = new PriorityQueue<>(0, comp);
Node root = new Node();
root.newNode(initial, x, y, x, y, 0, null);
root.cost = calculateCost(initial, fin);
pq.add(root);
while(!pq.isEmpty()) {
Node min = pq.peek();
pq.remove();
if(min.cost == 0) {
printPath(min);
return;
}
for (int i = 0; i < 4; i++) {
if(isSafe(min.x + row[i], min.y + col[i]) == 1) {
Node child = new Node();
child.newNode(min.mat, min.x, min.y, min.x + row[i], min.y + col[i], min.level + 1, min);
child.cost = calculateCost(child.mat, fin);
pq.add(child);
}
}
}
}
public static void main(String[] args) {
int[][] initial =
{
{1, 2, 3},
{5, 6, 0},
{7, 8, 4}
};
int[][] fin =
{
{1, 2, 3},
{5, 0, 6},
{8, 7, 4}
};
int x = 1, y = 2;
Node newNode = new Node();
newNode.solve(initial, x, y, fin);
}
}
答案 0 :(得分:3)
来自javadoc(强调是我的):
public PriorityQueue(int initialCapacity, Comparator<? super E> comparator)
创建一个具有指定初始容量的
PriorityQueue
,该容量根据指定的比较器对其元素进行排序。[...]
<强>抛出: IllegalArgumentException - 如果initialCapacity小于1