I'm trying to solve 15-puzzle (sliding puzzle) with iterative deepening search.
This is my initial state :
1 2 12 13
5 6 7 8
9 3 4 0
11 14 15 10
And this is my goal state :
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 0
I have a class of node to represent my state. This class looks like that :
public List<Node> children = new LinkedList<Node>();
public Node parent;
public static final int size = 4;
public int[][] puzzle = new int[size][size];
public int depth = 0;
And here is my search function :
public List<Node> ids(Node root) {
List<Node> path = new LinkedList<Node>();
boolean goal = false;
for(int limit=0; !goal; limit++) {
path = dfs(root,limit);
if(!path.isEmpty())
goal = true;
}
return path;
}
public List<Node> dfs(Node root, int limit) {
List<Node> path = new LinkedList<Node>();
PriorityQueue<Node> queue = new PriorityQueue<Node>(10000, new Comparator<Node>() {
public int compare(Node n1, Node n2) {
int depth1 = n1.depth;
int depth2 = n2.depth;
if(depth1 > depth2)
return 1;
else if(depth1 < depth2)
return -1;
return Node.comparePuzzle(n1.puzzle, n2.puzzle);
}
});
List<Node> expendList = new LinkedList<Node>();
List<Node> expended = new LinkedList<Node>();
queue.add(root);
boolean goal = false;
while(!queue.isEmpty() && !goal) {
Node temp = queue.poll();
expended.add(temp);
if(!temp.isGoal()) {
temp.expend();
for(int i=0; i<temp.children.size(); i++) {
Node child = temp.children.get(i);
child.setDepth(temp.getDepth() + 1);
expendList.addAll(queue);
if(!contains(expendList,child) && !contains(expended,child) && child.depth < limit)
{
queue.add(child);
}
}
} else {
goal = true;
pathTrace(path,temp);
}
}
return path;
}
The goal state is in depth 9 of the search tree but my function gets stuck in limit 6 and I don't know why. When the goal is in depth 6 or less the function finds the solution but when the depth is more than 6 the function runs a lot of time and gets stuck.