Heuristica() method of problema_puzzles.
The evaluation function
Theevaluacion() function counts how many tiles are in the wrong position compared to the goal state, ignoring the blank space.
0. A puzzle with all eight tiles out of place returns 8. Lower is better.
The blank tile (
' ') is deliberately excluded from the count. Moving the blank is just a mechanism—what matters is where the numbered tiles end up.The priority queue and operator<
Heuristica() replaces the std::list used by BFS/DFS with a std::priority_queue<puzzle>. A priority_queue always gives you the element with the highest priority first, which by default means the largest value.
Because a lower evaluation score is better, the operator< is intentionally inverted:
*this is considered less than other when *this has a higher eval score.” A higher eval score means more tiles out of place, which means lower priority. The effect is that the puzzle with the fewest misplaced tiles always surfaces at the top of the queue.
How Heuristica() runs
Push the initial state
The starting puzzle is pushed onto the priority queue with its evaluation score (typically computed before insertion for children; the initial state starts with
eval = 0 by default).Pop the best state
Each iteration takes the state with the lowest evaluation score—the one closest to the goal.
Check for the goal
The same cell-by-cell comparison used in BFS and DFS checks whether
aux matches meta. If it does, the algorithm stops and prints the move sequence.Why heuristic search is faster in practice
Consider the predefined example inmain():
The heuristic used here—counting misplaced tiles—is called the Hamming distance. It is an admissible heuristic for the 8-Puzzle because it never overestimates the number of moves needed (you need at least one move per misplaced tile).
BFS / DFS vs heuristic search
| Property | BFS | DFS | Heuristic |
|---|---|---|---|
| Expansion order | Shallowest first | Deepest first | Best score first |
| Finds shortest path? | Yes | Not guaranteed | Not guaranteed (greedy) |
| Memory usage | High | Low | Medium |
| Speed on hard puzzles | Slow | Unpredictable | Fast |
| Requires evaluation function? | No | No | Yes |
| Data structure | std::list as queue | std::list as stack | std::priority_queue |