ai-22 / src / am / aua / search / BestFirstGraphSearch.java
BestFirstGraphSearch.java
Raw
package am.aua.search;

import java.util.HashMap;

public class BestFirstGraphSearch implements Search {
    private Frontier frontier;
    private NodeFunction f;

    // statistics
    // keeps track of how many nodes where generated during last search
    private int steps;

    public BestFirstGraphSearch(NodeFunction f) {
        this.f = f;
        frontier = new BestFirstFrontier(f);

        steps = 0;
    }

    @Override
    public Node search(State initialState, GoalTest test) {
        frontier.clear();
        steps = 1;

        Node node = new Node(null, null, initialState);
        if (test.isGoal(node.state))
            return node;
        frontier.add(node);
        HashMap<State, Node> reached = new HashMap<>();
        reached.put(node.state, node);
        while (!frontier.isEmpty()) {
            node = frontier.remove();
            if (test.isGoal(node.state)) return node;
            for (Action action : node.state.getApplicableActions()) {
                State newState = node.state.getActionResult(action);
                Node child = new Node(node, action, newState);
                steps++;
                if (!reached.containsKey(newState) || child.pathCost < reached.get(newState).pathCost) {
                    reached.put(newState, child);
                    frontier.add(child);
                }
            }
        }
        return null;
    }


    @Override
    public int steps() {
        return steps;
    }

    @Override
    public int stretchFactor() {
        return frontier.stretchFactor();
    }

    @Override
    public String toString() {
        return frontier + " Graph Search";
    }
}