-
Notifications
You must be signed in to change notification settings - Fork 67
Examples
The n-puzzle problem is the general case of the more familiar 15-puzzle. It is a sliding tile game where the object is to slide one tile at a time until all the tiles are in a specific order. Using A* it is possible to find the shortest sequence of moves that will result in a solved puzzle.
The n-puzzle
executable takes two arguments on the command line, a file from which the starting state will be read, and a file from which the goal state will be read. Only the first line is read from each file. Sample files are provided in the input
directory.
If the project is built using CMake, then it can be run from the n-puzzle
directory with:
./bin/n-puzzle input/start input/goal
The input is simply a sequence of whitespace separated numbers representing an n-by-n puzzle, with zero representing the empty space. The number of elements determines the size of the puzzle; 4 elements for a 2x2 puzzle, 9 for a 3x3, and so forth. The numbers are in row-major order; if there are 9 numbers, the first 3 are the top row of the puzzle, the next 3 are the middle row, and the last 3 are the bottom row.
There is some validation to ensure that a puzzle is square and that there is a blank space.
The program solves the starting puzzle 3 times, each with a different heuristic function. The functions are:
- Displacement - a count of how many tiles are out of place
- Manhattan Distance - the sum of how many rows and columns each tile is from its final location in the goal state
- The sum of the displacement and manhattan heuristics.
The best path determined by each heuristic is written to a corresponding file: displaced.txt
, manhattan.txt
, and displaced-manhattan.txt
.