简体   繁体   中英

Java Breadth First Search - 8 Slider

The question is this, breadth first search needs to sort a board array of 9 values. 1,2,3,4,5,6,7,8,0.. In order, was told not to modify most of the existing code, and to add BFS and other statements in numerous class files. The run time is giving 1,2,5,3,4,8,6,7,0. It is moving the 0 properly, but as to the path, not sure what to add to the existing code in order to resolve this so that the pathing and numbers resolve.


  while (!frontier.isEmpty()) {
    cur = frontier.remove();
    if (cur.isGoal()) {
      return cur;
    } else if (cur.getDepth() < 15) {
      visited.add(cur);
      for (Node s : cur.expand()) {
        if (!visited.contains(s)) {
          s.setParent(cur);
          s.setDepth(cur.getDepth() + 1);
          frontier.add(s);
          numNodesExplored++;
        }
      }
    }
  }
    return null;

You mention in the comments that you aspect a output like 1, 2, 3, 4, 5, 6, 7, 8, 0 . This is not possible with the method runBFS . When you look at the method signature Node runBFS(Node start) you can see that this method returns a Node and not a List of Nodes.

Additional to that you have a logical error. In the bellow code-block you can see that you add to a Node s his parent to s . With other words: s is his own parent.

if (!explored.contains(s)) {
    s.setParent(s);   // here you add the wrong parent - it should be s.setParent(cur)
    s.setDepth(cur.getDepth() + 1);
    frontier.add(s);
    numNodesExplored++;
}

Just change the line to s.setParent(cur) . cur is the Node you are looking for his siblings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM