6

我作为一个学校练习在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;
    }

谢谢

4

2 回答 2

8
frontier.addNodeToFront(child);

assuming the rest of your code (getReachableStatesFrom(), etc) is correct, adding elements to the front of your queue will cause your code to execute as a depth first search.

于 2012-09-23T19:34:09.953 回答
0

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

于 2016-08-07T00:16:49.310 回答