广度优先搜索 - Java

mrj*_*min 6 java algorithm search breadth-first-search

我有一个学校,在java中实现广度优先搜索.我已经实现了几乎所有的东西,但问题是我的搜索不起作用,我无法找到问题:(所以我要求你给我建议,并给我一些关于最终问题可能出现的指导.

public ArrayList<SearchNode> search(Problem p) {
        // The frontier is a queue of expanded SearchNodes not processed yet
        frontier = new NodeQueue();
        /// The explored set is a set of nodes that have been processed 
        explored = new HashSet<SearchNode>();
        // The start state is given
        GridPos startState = (GridPos) p.getInitialState();
        // Initialize the frontier with the start state  
        frontier.addNodeToFront(new SearchNode(startState));

        // Path will be empty until we find the goal.
        path = new ArrayList<SearchNode>();

        // The start NODE

        SearchNode node = new SearchNode(startState); 

        // Check if startState = GoalState??
        if(p.isGoalState(startState)){
           path.add(new SearchNode(startState)); 
           return path; 
        }


        do {  

          node = frontier.removeFirst();
          explored.add(node); 

          ArrayList reachable = new ArrayList<GridPos>();
          reachable = p.getReachableStatesFrom(node.getState()); 

          SearchNode child; 

          for(int i = 0; i< reachable.size(); i++){

              child = new SearchNode((GridPos)reachable.get(i)); 

              if(!(explored.contains(child) || frontier.contains(child))){
                  if(p.isGoalState(child.getState())){
                      path = child.getPathFromRoot() ;  
                      return path; 
                  }
                  frontier.addNodeToFront(child); 
              }

          }
        }while(!frontier.isEmpty());


        return path;
    }
Run Code Online (Sandbox Code Playgroud)

谢谢

Ale*_*nch 8

frontier.addNodeToFront(child);
Run Code Online (Sandbox Code Playgroud)

假设您的其余代码(getReachableStatesFrom()等)是正确的,将元素添加到队列的前面将导致您的代码作为深度优先搜索执行.

  • @ user1285737如果你能找到你的代码可能有问题的另一个地方,可以随意打开另一个问题:)如果你认为我已经适当地回答了这个问题,接受我的答案是感谢的首选方式.祝好运! (2认同)