繁体   English   中英

广度优先搜索 - Java

[英]Breadth First Search - Java

我有一个学校,在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;
    }

谢谢

frontier.addNodeToFront(child);

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

要实现广度优先搜索,您应该使用队列。 这个过程可能会变得非常复杂。 所以,最好保持简单。 您应该将节点的子节点推送到队列(左侧和右侧),然后访问节点(打印数据)。 然后,你应该从队列中删除节点。 您应该继续此过程,直到队列变空。 你可以在这里看到我对BFS的实现: https//github.com/m-vahidalizadeh/foundations/blob/master/src/algorithms/TreeTraverse.java

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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