Code

graph.go — the skeleton

Create graph.go. The usual skeleton; the bodies are yours.

Worth noting:

  • c.Hit() counts EDGES, not nodes — call it where you consider whether to follow an edge. That is the "E" in O(V + E).
  • AddEdge must reject self-loops and duplicates. The trail generator produces both, and a duplicated edge quietly inflates every number in this lesson.
  • Use a counting sort for Degrees' median (lesson 9), not a comparison sort — the degree range is tiny, which is exactly that case.

Where it goes wrong

BFS marks seen when PUTTING, DFS when TAKING. It looks like a detail and is not.

BFS: mark a node the moment you put it in the queue. Mark it only on the way out and the same node enters the queue several times across different layers, and prev[w] gets overwritten by a longer route. The search still finds a path — just no longer the shortest. The test will catch it, but you should catch it first.

DFS: the opposite. A node can legitimately be pushed several times before its turn comes, so the check belongs where you take.

The same line, two different places, and the reason is the same both times: a queue visits in layers and a stack does not.

Gotcha

DFS and DFSRecursive will return different paths, and that is not a bug.

The stack version pushes all the neighbours and then takes the last one; the recursive version walks them in order from the first. The neighbour visiting order is reversed, so the trails differ.

Both paths are real, both arrive, and neither is shortest. TestTheTwoDFSVersionsDisagreeOnPaths requires them to differ — drill 2 is about making them agree.