【发布时间】:2013-11-06 22:36:47
【问题描述】:
我实现了迭代深化 a-star 搜索(针对 8-Puzzle 问题,但可以接受其他问题)并在输入上运行它。它运行了2小时不成功。对于接近目标节点的简单输入,它可以正常工作。其他人已经让它为这个输入工作。我不确定我的实现是效率低下还是进入了无限循环
PuzzleSolver.java$ida
/** Accepts start node root and string identifying whihc heuristic to use
* h1 is number of misplaced tiles and h2 is Manhattan distance
*/
private Node ida(Node root, final String h) {
PriorityQueue<DNode> frontier = new PriorityQueue<DNode>(10, new Comparator<DNode>(){
@Override
public int compare(DNode n1, DNode n2) {
if(h == "h1") {
if(n1.depth + h1(n1.node) > n2.depth + h1(n2.node)) return 1;
if(n1.depth + h1(n1.node) < n2.depth + h1(n2.node)) return -1;
return 0;
}
if(h == "h2") {
if(n1.depth + h2(n1.node) > n2.depth + h2(n2.node)) return 1;
if(n1.depth + h2(n1.node) < n2.depth + h2(n2.node)) return -1;
return 0;
}
return 0;
}});
ArrayList<Node> explored = new ArrayList<Node>();
Node soln = null;
DNode start = new DNode(root, 1);
frontier.add(start);
int d = 0;
int flimit = (h == "h1" ? h1(start.node) : h2(start.node));
int min = flimit;
while(true) {
DNode dn = frontier.poll();
if(dn == null) {
frontier.add(start);
d = 0;
flimit = min;
continue;
}
d = dn.depth;
Node n = dn.node;
//n.print();
if(goalCheck(n)){
return n;
}
for(int i = 0;i < ops.length;i++) {
String op = ops[i];
if(n.applicable(op)) {
soln = n.applyOp(op);
int h_cost;
if(h == "h1") h_cost = h1(soln);
else h_cost = h2(soln);
if(!checkDup(explored,soln) && d + 1 + h_cost < flimit) {
frontier.add(new DNode(soln, d + 1));
DNode least = frontier.peek();
min = least.depth + (h == "h1" ? h1(least.node) : h2(least.node));
}
}
}
explored.add(n);
max_list_size = Math.max(max_list_size, frontier.size() + explored.size());
}
}
PuzzleSolver.java$CheckDup
private boolean checkDup(ArrayList<Node> explored, Node soln) {
boolean isDuplicate = false;
for(Node n:explored) {
boolean equal = true;
for(int i = 0;i < soln.size; i++) {
for(int j =0 ;j<soln.size;j++) {
if(soln.state.get(i).get(j) != n.state.get(i).get(j)) {
equal = false;
}
}
}
isDuplicate |= equal;
}
return isDuplicate;
}
开始状态(失败):
1 2 3
8 - 4
7 6 5
目标状态:
1 3 4
8 6 2
7 - 5
(为 1 3 4 8 6 0 7 5 2 工作) 我没有包含 Node.java,因为我很确定它在运行其他搜索算法(如最佳优先、dfs)后可以工作。提供 SCCE 很困难,所以我只是请求帮助发现 ida 实现中的任何明显错误。
编辑:已解决问题,但在无法达到目标时仍试图找出终止条件。 IDA* 不保留已探索节点的列表,那么我如何知道我是否已经覆盖了整个解决方案空间?
【问题讨论】:
-
强制性 8 题注释:请注意,实际上只有一半的起始状态是可解决的,并确保在考虑调试代码之前不要尝试解决其中之一。
-
是的,目标节点可达
-
这是this question的交叉帖子吗? You shouldn't cross-post.
标签: java search artificial-intelligence sliding-tile-puzzle