11521111DBGEACFseenqueuefront: oldest outback: new inABCDEFGseen
Nodes: glow once seen; the front number is edges from AEdges: rose = the ones this step uses, green = the fewest-edge routeFrontier: a queue for BFS, a stack for DFSSeen set: every node already foundBreadth-first search keeps its frontier in a queue: the letter that joined first leaves first, so the search finishes every node 1 edge from A before any node 2 edges away. Depth-first search keeps its open calls on a stack: the newest leaves first, so it dives down one path and backs up at dead ends. A glow means the node is in the seen set, so it is never added twice. The number on a node's front is how many edges from A the search found it: BFS gives the fewest; DFS can be much deeper. In the last step the edges carry costs, and Dijkstra's algorithm finds the cheapest route instead.

The graph

  1. A graph is a set of nodes joined by edges. Here, 7 nodes and 8 edges. Each node keeps a list of its neighbours, the nodes one edge away. To search is to visit every node you can reach from A.

Breadth-first

Depth-first

Compare

The same thing in Python

# step 1/12 · A graph: nodes and edges
graph = {
    "A": ["B", "C"],      "B": ["A", "D", "E"],
    "C": ["A", "F"],      "D": ["B", "G"],
    "E": ["B", "G"],      "F": ["C", "G"],
    "G": ["D", "E", "F"],
}
>>> graph["B"]          # B's neighbours
['A', 'D', 'E']

A Python set has no order. The drawing lists the seen set in the order nodes were added, to make it easy to follow. Both searches try neighbours in alphabetical order. A different order gives a different but equally valid visit order; BFS distances stay the same.