BFS — fill in two holes
In the last step you watched BFS in a table. Now the same thing is written down as an algorithm — and you fill in two missing pieces.
Pseudocode
BFS(from, to):
prev[*] ← −1; seen[from] ← true
queue ← [from]
while queue is not empty:
v ← FRONT of queue
if v = to: return the path
for each neighbour w:
c.Hit()
if seen[w]: skip
seen[w] ← true
prev[w] ← v
queue ← queue + w
return "no path"
This is exactly what you did by hand in the table: take a node from the front, look at its neighbours; mark the new ones, remember where you came from, and stand them at the back of the queue.
prev[w] is the answer to "where did I come from to get here". When to is
found, you walk back through prev to from — that is the path. rebuild
already does that reversal.
Why the first find is the shortest. A queue visits in layers: everything one
hop away first, then everything two hops away. When to reaches the front, there
is no shorter layer left.
Your job
Create three files (see the panel): graph.go, trails.go and graph_test.go.
trails.go— the "readers also borrowed" generator. It is complete and not your task: it is the test data that the tests and, later, the measurement use. It builds trails, not random pairs, and that matters in step 9.graph.go— the skeleton. The graph itself (NewGraph,AddEdge,Neighbors) is already written: it is storage, not the lesson.AddEdgedrops self-loops and duplicates — the trail generator produces both, and a duplicated edge would quietly inflate every number in this lesson.c.Hit()counts EDGES, not nodes — that is the "E" inO(V + E).graph_test.go— the verdict. You do not write it, you pass it. For now it checks BFS only.
BFS is complete and compiles, but it does not work: the loops are written
and two places are missing. They are marked HOLE 1 and HOLE 2:
- HOLE 1 — when to skip a neighbour. In the pseudocode that is
if seen[w]: skip. Replacefalsewith a real condition. - HOLE 2 — the neighbour is new: mark it seen, remember
prev[w], and put it at the back of the queue. Three lines. Delete the_ = wline — it is only there so the skeleton compiles.
Nothing else needs changing. The loops already contain c.Hit(), taking from the
front, and rebuild.
The test also checks the table from the last step: 0 → 6 must return the path
[0 1 6] and look at 6 edges. If your code counts differently, something is
off even if the path is right.
Run the test before you fill anything in
Run it as it stands first:
$ go test ./...
--- FAIL: TestBFSReproducesTheTable (0.00s)
graph_test.go:84: BFS 0 to 6: found=false path=[], 2 edges looked at; want path [0 1 6], 6 edges
--- FAIL: TestBFSFindsTheShortestPath (0.00s)
graph_test.go:106: BFS missed 2, which is 6 hops away
FAIL
That is not an error — it is the starting point. The skeleton looks at the two
edges of 0 (2 edges looked at), puts neither in the queue, and the queue runs
dry. It reached nothing, not even a neighbour.
Fill in both holes and run it again — you should see ok.
When it does not pass
found=false … 2 edges looked at— nothing entered the queue. Either the HOLE 1 condition is inverted (!seen[w]skips the new ones), or HOLE 2 is empty, or thequeue = append(queue, w)is missing.path=[6], and in the other testnot a path to 2: [2]— you queued the node but did not recordprev[w] = v. Whentois found, the chain back breaks at once.8 edges looked at, want 6— HOLE 1 is stillfalse: you skipped no neighbour at all. The path is still right, but every node is queued several times.panic: BFS queue is longer than the number of nodes— you forgotseen[w] = true. Without it every neighbour keeps re-entering the queue, and an unreachable target is searched for forever. Thatpanicis a safety valve written at the top of the loop: without it the program would swallow memory at gigabytes per second.path=[0 2 3 4 5 6], 12 edges looked at— you put the neighbour at the front of the queue instead of the back. That is no longer a queue — it is a stack, and you just wrote DFS. It arrives in the next step.
Where it goes wrong
BFS marks seen when PUTTING, not when TAKING. It looks like a detail and is
not.
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. Drill 2 makes you do it on purpose.