liveBook · Manning

Astar

As explained in Classic Computer Science Problems in Swift: Essential techniques for practicing programmers

astar is a book-specific function that performs A* search over maze states.

A* search finds a path through a maze by combining accumulated path cost with a heuristic estimate of the remaining distance. It resembles BFS, but replaces its queue with a priority queue ordered by f(n) = g(n) + h(n). section 2.2

The Swift implementation changes the generic search machinery in several focused ways:

  • Stores frontier nodes in an ascending priority queue, so the lowest f(n) is selected next. section 2.2
  • Tracks each explored state's lowest known g(n) in a dictionary, allowing a cheaper route to replace an earlier one. section 2.2
  • Assigns every maze hop a cost of 1 and receives the heuristic through heuristicFn(). section 2.2
  • Uses Manhattan distance for four-direction movement, while Euclidean distance provides an alternative estimate. section 2.2

Searching a generated maze

Generate a 10-by-10 maze, then call astar(initialState: start, goalTestFn: goalTest, successorFn: successorsForMaze(maze3), heuristicFn: manhattanDistance). Convert the returned node with nodeToPath, mark the path, and print the maze. section 2.2

// A Cell represents the status of a grid location in the maze
enum Cell: Character {
    case Empty = "O"
    case Blocked = "X"
    case Start = "S"
    case Goal = "G"
    case Path = "P"
}

typealias Maze = [[Cell]]

Use the Cell enum and Maze type to represent empty, blocked, start, goal, and path locations in the grid. section 2.2

How Classic Computer Science Problems in Swift: Essential techniques for practicing programmers covers it

How deep it goes
Defines frontier ordering, cost tracking, heuristic injection, and cheaper-route replacement, but omits a full implementation listing.
Examples
Uses generated 10-by-10 mazes, Manhattan distance, Euclidean distance, maze cells, and printed paths.
What it assumes
Builds on BFS-style frontier and explored-state patterns, while assuming familiarity with generic search functions.
What you can do after
Build A* maze searches in Swift using state, goal, successor, and heuristic functions.
How it connects
Connects A* with DFS, BFS, priority queues, heuristics, admissible heuristics, and maze path reconstruction.

This explainer was generated by Manning's knowledge graph from the text of Classic Computer Science Problems in Swift: Essential techniques for practicing programmers. The section links point to the parts of the book it draws on.