liveBook · Manning

Breadth-first search

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

A graph or state-space search algorithm that explores all states at the current distance before proceeding to greater distances.

To find a route through a maze, start at one location and examine reachable locations one move away before moving farther out. Breadth-first search (BFS) explores the closest states first. In a small graph, this often makes it sufficient for finding a shortest path. section 2.2 section 2.4

public class Queue<T> {
    private var container: [T] = [T]()
    public var isEmpty: Bool { return container.isEmpty }
    public func push(thing: T) { container.append(thing) }
    public func pop() -> T { return container.removeFirst() }
}

The queue is the key change from depth-first search: new nodes go to the back, and the next node comes from the front. section 2.2

A generic Swift search needs an initial state, a goal test, and a function that returns successors:

  • Put the initial state in the queue as a node with no parent, and add its state to an explored set. section 2.2
  • Remove the front node. If it passes the goal test, return it. Otherwise, enqueue each unexplored successor, recording the current node as its parent and marking the successor explored. section 2.2
  • Follow parent links backward from a returned goal node to recover the path. section 2.2

A four-way maze

Represent the maze as a grid of open and blocked cells. From each location, generate unblocked neighbors above, below, left, and right—never diagonally. A search from (0, 0) toward (9, 9) can then produce a path to mark and print on the grid. section 2.2

Depth-first search uses a stack instead and may follow one route deep before trying another. For a larger graph with a useful heuristic, A* is an alternative to BFS. section 2.2 section 2.4

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

How deep it goes
Works through a generic queue-based implementation, explored states, goal testing, and parent-linked path reconstruction.
Examples
Uses a randomly generated grid maze, four-way movement, and a printed path from start to goal.
What it assumes
Assumes familiarity with Swift functions and generic types while defining the maze representation, locations, and queue used in the search.
What you can do after
Build it from scratch as a generic Swift search and apply it to mark a route through a maze.
How it connects
Contrasts with depth-first search and connects to A*, uniform-cost search, and backtracking search.

Also explained in

Compare how 8 books explain breadth-first search →

Related concepts

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.