Sub topic 1
Framing Pathfinding as Graph Search
Prerequisites
This chapter assumes you can read basic Python, know what nodes, edges, and edge weights are, understand breadth-first search, and know that a priority queue always returns its smallest item first.
Search Problems as Weighted Graphs
A search problem has a start state, a goal test, and a set of moves. Each move has a cost. Model each state as a node and each move as a weighted edge, and pathfinding becomes the task of finding the least-cost path from start to goal. On a grid map, each open cell is a node. Each step to an adjacent cell is an edge with cost 1.
Breadth-first search finds the path with the fewest edges. That path is the cheapest one only when every edge costs the same. When edge costs differ, you need a search that keeps track of cost.
Uniform-Cost Search: Expanding by Cost So Far
Uniform-cost search, which is Dijkstra's algorithm stopped at the goal, keeps a priority queue ordered by g(n). This is the cost of the cheapest path found so far from the start to n. It always expands the frontier node with the lowest g. The first time it removes the goal from the queue, it has found an optimal path. It has no sense of direction, though. It spreads outward in every direction, including away from the goal.
Greedy Best-First Search: Expanding by Estimated Distance
Greedy best-first search orders the queue by h(n) alone. The value h(n) is a heuristic: an estimate of the remaining cost from n to the goal, such as straight-line distance. Greedy search heads toward the goal fast. It ignores the cost already paid, so it can commit to a long detour and return a path that is not optimal.
Combining Both: f(n) = g(n) + h(n)
A* ranks each node by
f(n) = g(n) + h(n)
which estimates the total cost of the best path through n. Each special case gives one of the earlier algorithms:
| Setting | Ordering | Behaves like |
|---|---|---|
| h(n) = 0 | g(n) | Uniform-cost search |
| g ignored | h(n) | Greedy best-first |
| both terms | g(n) + h(n) | A* |
How A* Works Step by Step
- Put the start node in the open list with g = 0 and f = h(start).
- Pop the node with the lowest f.
- If it is the goal, follow parent links back to the start to rebuild the path.
- Otherwise, for each neighbor, compute newg = g(node) + edge cost. If newg beats the neighbor's best known g, record it, set its parent, and push it with f = new_g + h(neighbor).
- Repeat until the open list is empty, which means no path exists.
Exercise
Node A has g = 4 and h = 6. Node B has g = 7 and h = 2. Which node does A* expand first, and which would greedy best-first expand first?
Show answer
A* expands B first, because f(B) = 9 and f(A) = 10. Greedy best-first also expands B first, because h(B) = 2 is lower than h(A) = 6. Uniform-cost search would expand A first, because g(A) = 4 is lower than g(B) = 7.