ai-22 / src / am / aua / npuzzle / ManhattanDistanceHeuristic.java
ManhattanDistanceHeuristic.java
Raw
package am.aua.npuzzle;

import am.aua.search.GoalTest;
import am.aua.search.Node;
import am.aua.search.NodeFunction;

/**
 * Heuristic 2.
 */
import static am.aua.utils.ArrayUtils.*;

public class ManhattanDistanceHeuristic implements NodeFunction {
    private GoalTest goalTest;

    public ManhattanDistanceHeuristic(GoalTest goalTest) {
        this.goalTest = goalTest;
    }

    @Override
    public int eval(Node n) {
        Tiles tiles = (Tiles) n.state;
        TilesGoalTest tilesGoalTest = (TilesGoalTest) goalTest;
        int dist = 0;
        for (int i = 0; i < tiles.width * tiles.width; i++) {
            int cell = tilesGoalTest.GOAL[i];
            int col = i % tiles.width;
            int row = i / tiles.width;
            dist += Math.abs(getCol(cell, tiles.tiles, tiles.width) - col); // horizontal
            dist += Math.abs(getRow(cell, tiles.tiles, tiles.width) - row); // vertical
        }
        return dist;
    }
}