Ejemplo n.º 1
0
int manhattan(const Puzzle& state, const Puzzle& solution) {
    int result = -1;

    /*
     * These loops compare two vectors piece by piece,
     * finding the row and column indeces for corresponding
     * pieces, and adding the magnitudes of the differences.
     *
     * This is presently O(n^2).
     * TODO: investigate O(n) solution
     */
    if(state.get_width() == solution.get_width()) {
        size_t width = state.get_width();
        int i = 0;
        for(TileIt it1 = state.tiles.begin(); it1 != state.tiles.end(); it1++, i++) {
            if(*it1 != 0) {

                int j = 0;
                for(TileIt it2 = solution.tiles.begin(); *it1 != *it2; it2++, j++);

                int r1 = i / width;
                int r2 = j / width;
                int c1 = i % width;
                int c2 = j % width;

                result += abs(r2 - r1) + abs(c2 - c1);
            }
        }
    }

    return result;
}
Ejemplo n.º 2
0
/*
 * These are the three examined heuristic functions.
 * displaced(...) counts how many tiles are out of place
 * manhattan(...) determines how far away each tile is from
 * its correct location, as specified in the solution.
 * sumdisman(...) simply sums displaced(...) and manhattan(...).
 */
int displaced(const Puzzle& state, const Puzzle& solution) {
    int result = -1;

    if(state.get_width() == solution.get_width()) {
        result = 0;

        for(TileIt it1 = state.tiles.begin(), it2 = solution.tiles.begin(); it1 != state.tiles.end(); it1++, it2++) {
            if(*it1 != 0 && *it1 != *it2) {
                result++;
            }
        }
    }

    return result;
}