首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >广度优先搜索- Java

广度优先搜索- Java
EN

Stack Overflow用户
提问于 2012-09-24 03:23:47
回答 2查看 10.7K关注 0票数 6

作为学校摘录,我在java中实现了广度优先搜索。我已经实现了几乎所有的东西,但问题是我的搜索不起作用,我找不到问题:(所以我请你给我一些建议,并给我一些指导,最终的问题可能在哪里。

代码语言:javascript
复制
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;
    }

谢谢

EN

回答 2

Stack Overflow用户

发布于 2012-09-24 03:34:10

代码语言:javascript
复制
frontier.addNodeToFront(child);

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

票数 8
EN

Stack Overflow用户

发布于 2016-08-07 08:16:49

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12555501

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档