Heuristic Search
The Compass in the Maze
Remember our maze from state space search? BFS and DFS are blind β they don't know which direction the exit is. They just explore systematically and hope for the best.
Now imagine you have a compass that always points toward the exit. You still can't see through walls, but you have a sense of direction. When you reach a fork, you pick the path that feels closer to the goal.
That compass is a heuristic β an educated guess about how close you are to the solution. It doesn't guarantee you're right, but it dramatically speeds up the search.
What Exactly is a Heuristic?
A heuristic is a function h(n) that estimates the cost from a node n to the goal. It's not exact β it's an approximation. For example:
- GPS navigation: the straight-line distance to your destination (ignoring roads)
- Sliding puzzle: how many tiles are in the wrong position
- Chess: the total value of your pieces minus your opponent's pieces
The key insight: a good heuristic doesn't need to be perfect. It just needs to point you in roughly the right direction. Even a mediocre compass is better than no compass at all.
Greedy Best-First Search
The simplest heuristic search is Greedy Best-First Search. At every step, it picks the node that looks closest to the goal according to the heuristic. It's fast, but it can be fooled β like following a compass straight into a wall.
A* Search: The Gold Standard
A* (A-star) is the most famous heuristic search algorithm. It combines two pieces of information:
g(n)β the actual cost to reach nodenfrom the starth(n)β the estimated cost fromnto the goal (the heuristic)
A* picks the node with the lowest f(n) = g(n) + h(n). This balances "how far I've come" with "how far I think I have left."
The magic of A*: if your heuristic never overestimates the true cost (we call this admissible), A* is guaranteed to find the shortest path. You get the optimality of BFS with the speed of a heuristic. Best of both worlds.
A* Search Implementation
Where A* Shows Up in Real Life
A* is one of the most widely used algorithms in the world:
- Video games β every time an NPC walks around obstacles to reach you, that's A*.
- GPS apps β Google Maps and Waze use variants of A* to find the fastest route.
- Robotics β robots use A* to plan paths around furniture, people, and other obstacles.
- Puzzle solvers β A* can solve sliding puzzles, mazes, and even Rubik's Cubes efficiently.
The beauty of A* is that it's simple, optimal, and flexible. Change the heuristic, and the same algorithm works for completely different problems.