BreadthFirstSearcher Code



import java.util.Vector;

/**
 * BreadthFirstSearcher.java - a simple implementation of
 * breadth-first search.
 *
 * @author Todd Neller
 * @version 1.0
 *
 */

public class BreadthFirstSearcher extends Searcher {
        
    /**
     * variable q - a queue to keep track of
     * the intersections involved in the search */
    private Queue q;

    /**
     * Creates a new BreadthFirstSearcher instance. */
    public BreadthFirstSearcher() {}
 
    /**
     * search - Search for a goal node starting at the
     * given "root" MapNode, and return whether or not a goal node
     * was found.
     *
     * @param rootNode a MapNode value - the initial
     * "root" search node
     * @return a boolean value - whether or not a goal
     * node was found */
    public boolean search(MapNode rootNode) {

    	q = new Queue(rootNode.map.length);
    	q.enqueue(rootNode);

	while (!q.isEmpty()) {			
	    MapNode tempNode = (MapNode)q.dequeue();			

	    if (tempNode.isGoal()){
		goalNode = tempNode;
		
		return true;
	    } else {
		Vector v = tempNode.expand();
		
		for (int i = 0; i < v.size(); i++) { 
		    q.enqueue(v.elementAt(i));
		}
	    }
	} return false;
    }
	
    /**
     * getNodeCount - Returns the number of nodes
     * examined (goal-checked) in the previous search.
     *
     * @return an int value - the number of nodes checked
     * in the previous search.  This may be considerably less than the
     * number of children generated. */
    public int getNodeCount() {
	return goalNode.depth;
    }
 
    /**
     * getGoalPath - If the previous search was
     * successful, add each node along the goal path  to an int 
     * arrayin sequence starting with the root node.
     *
     * @param length an int value
     * @return an int[] value  */
    public int[] getGoalPath(int length) {
	return getPath(goalNode, length);
    }

    /**
     * getPath - add each node along the path to an
     * int array in sequence starting with the root node.
     *
     * @param node a MapNode value
     * @param length an int value
     * @return an int[] value  */
    private int[] getPath(MapNode node, int length) {
	MapNode checker = (MapNode) node;
	int[] arr = new int[length + 1];
	int i = 0;
	arr[i] = checker.currentState;
	while(checker.parent != null) {
	    i++;
	    checker = (MapNode)checker.parent;
	    arr[i] = checker.currentState;
	} return arr;
    }
}