LOGBOOK

HELP

Quiz Entry - updated: 2026.11.27

How does DFS find a path between two vertices u and z, and what does its stack hold?

Run DFS from u and keep a stack S of the route from u to the current vertex: push each vertex when DFS enters it and each discovery edge before following it, and pop them again when DFS backs up. The moment DFS enters z, the stack holds a path from u to z, alternating vertices and edges, and the search stops.

pathDFS(G, v, z):
  label v VISITED;  S.push(v)
  if v = z:  finish, the result is S
  for each edge e of v that is UNEXPLORED:
    w ← opposite(v, e)
    if w is UNEXPLORED:
      label e DISCOVERY;  S.push(e)
      pathDFS(G, w, z)
      S.pop()                    // e
    else:
      label e BACK
  S.pop()                        // v: dead end, back up

pathDFS from A to E: the route A, B, C, E on the stack, the dead end at D, and the direct edge A-E that was never tried

* D was pushed and popped again as a dead end; the stack ends as A, A–B, B, B–C, C, C–E, E. *

The stack always mirrors the recursion: it holds the vertices of the calls still open, with the discovery edges between them, so when z is entered it lists one path from u to z. If DFS finishes without ever entering z, every push has been matched by a pop, S is empty again, and there is no path at all: z lies in another connected component.

In real code "finish" needs care. The calls for the vertices before z on the path are all still open, and each would pop its edge and its vertex on the way out, taking the result apart. So either copy S the moment z is entered, or let the call return true and have every caller return at once, skipping its pops.

DFS finds a path, not necessarily a short one. In the example the edge A–E alone joins the two vertices, but DFS happened to take A–B first and reached E only via B and C, three edges instead of one. A path with the fewest edges is what breadth-first search finds.

From Quiz: ADS / Graph Traversals: Depth-First and Breadth-First Search | Updated: Nov 27, 2026