当我尝试添加Node initialState(实现compareTo方法)时,我不确定为什么我会得到一个空指针。以下是我的Node类。
package puzzle;
public class Node implements Comparable<Node> {
int[][] state;
Node parent;
String action;
Node up, down, left, right;
int r,c;
int f;
Node(int[][] s, Node n,int row, int column){
state = s;
parent = n;
up = null;
down = null;
left = null;
right = null;
r = row;
c = column;
f = 0;
}
public void setF() {
int g = 0; // distance
int h = 0; // Manhattan distance
int k = 0;
for (int i = 0; i < state.length; i++){
for (int j = 0; j < state[i].length; j++){
if (state[i][j] != k)
g++;
k++;
}
}
// http://stackoverflow.com/questions/12526792/manhattan-distance-in-a
for (int x = 0; x < state.length; x++) { // x-dimension, traversing rows (i)
for (int y = 0; y < state[x].length; y++) { // y-dimension, traversing cols (j)
int value = state[x][y]; // tiles array contains board elements
if (value != 0) { // we don't compute MD for element 0
int targetX = (value) / state.length; // expected x-coordinate (row)
int targetY = (value) % state.length; // expected y-coordinate (col)
int dx = x - targetX; // x-distance to expected coordinate
int dy = y - targetY; // y-distance to expected coordinate
h += Math.abs(dx) + Math.abs(dy);
}
}
}
for(int i = 0; i < state.length; i++){
for (int j = 0; j < state.length; j++){
System.out.print(state[i][j]);
}
System.out.println();
}
System.out.println(h);
System.out.println(g);
f = h + g;
}
@Override
public int compareTo(Node node) {
if (this.f < node.f)
return -1;
else if (this.f > node.f)
return 1;
else return 0;
}
}
这里是异常发生的地方
private void Asearch() {
openListP = new PriorityQueue<Node>(1000);
closedList = new LinkedList<Node>();
initialState.setF();
//print(initialState);
openList.add(initialState); // initial state into open list
while (!openList.isEmpty()){
Node n = openListP.remove();
if (isGoal(n.state)){ // check if goal
printPath(n);
return;
}
else {
expandH(n); // expand to next frontier
closedList.add(n);
}
}
if(openList.isEmpty())
System.out.println(" unsolvable");
}
当我添加initialState时,我收到此错误
Exception in thread "main" java.lang.NullPointerException
at puzzle.Puzzle.Asearch(Puzzle.java:150)
at puzzle.Puzzle.solve(Puzzle.java:142)
at puzzle.Test.main(Test.java:11)
答案 0 :(得分:0)
您必须将openList更改为openListP。
openList.add(initialState); // initial state into open list
应该是
openListP.add(initialState); // initial state into open list