首页 > 解决方案 > 为什么我的 equals 语句不适用于我的广度优先搜索

问题描述

我正在编写一个程序来解决一个 8 块拼图但我没有得到任何输出,我正在运行调试器并且我正在生成正确的后继者,其中一个是我想要的目标状态但是当我比较它们时并没有说它们是这样,所以我的程序只是不断循环。有谁知道为什么会发生这种情况?

public static void BFSSearch(Node start, Node goal) {
    Queue<Node> q = new LinkedList<>();
    q.add(start);
    while (!q.isEmpty()) {
        Node theNode = q.poll();
        if (theNode.equals(goal)) {
            Stack<Node> path = new Stack<>();
            path.push(theNode);
            theNode = theNode.getParent();
            while (theNode.getParent() != null) {
                path.push(theNode);
                theNode = theNode.getParent();
            }
            path.push(theNode);
            int stackSize = path.size();
            for (int i = 0; i < stackSize; i++) {
                theNode = path.pop();
                theNode.printState();
            }
        } else {
            ArrayList<Node> successors = theNode.genSuccessors();
            for (int i = 0; i < successors.size(); i++) {
                Node newNode = new Node(successors.get(i).curr);
                if (newNode.equals(goal)){
                    System.out.println("found");
                }
                if (!checkRepeats(newNode)) {
                    ((LinkedList<Node>) q).add(newNode);
                }
            }
        }
    }
}

标签: javasearchbreadth-first-search

解决方案


推荐阅读