DFS, components, degrees, matrix — write them yourself
BFS works. The rest come without holes this time: empty skeletons, and you fill them in completely. First and most important — DFS.
DFS — depth-first
DFS(from, to):
prev[*] ← −1
stack ← [from]
while stack is not empty:
v ← BACK of stack // ← a stack; the ONLY difference
if seen[v]: skip
seen[v] ← true
if v = to: return the path
for each neighbour w:
c.Hit()
if seen[w]: skip
prev[w] ← v; stack ← stack + w
return "no path"
Compare with BFS. One line differs — FRONT of queue against BACK of stack
— plus one detail: DFS checks seen when it takes, not when it puts, because
the same node can be pushed several times before its turn comes.
A stack goes as deep as it can, hits a dead end, and backs up. There are no
layers, so there is no promise about length. On 0 → 6 it must return the path
[0 2 3 4 5 6] and look at 12 edges — exactly as in the table.
DFS is not meant to find the shortest path. Do not try to "fix" that: step 6 is about it, and the test requires it.
The recursive version
DFSRecursive(v):
seen[v] ← true
if v = to: found
for each neighbour w:
c.Hit()
if not seen[w]: prev[w] ← v; if DFSRecursive(w): found
There is no stack here — because there is one: the call stack. Lesson 5 already showed and measured that; step 7 shows where the equivalence has a limit.
On the same graph, 0 → 6, recursive DFS returns [0 1 6] and looks at only
3 edges. The same algorithm, a different path — and the test requires it.
Components
count ← 0; largest ← 0
for every node s:
if seen[s]: skip
count ← count + 1
sweep all of s's component with a queue (mark seen when PUTTING) and count its nodes
largest ← the larger of (largest, that count)
Every node is visited exactly once across the whole process, so the cost
stays O(V + E) — not V separate searches.
Degrees
A node's degree is its number of neighbours. You need three numbers: the mean, the median and the largest.
The degree range is tiny (up to 10 in this network), which is exactly the case for the counting sort of lesson 9: count how many nodes have each degree, then walk the counters until you have accumulated more than half. A comparison sort would be waste here.
The adjacency matrix
AdjMatrix is the second representation: one bit for every ordered pair
(a, b). Turn a pair into a single bit position a·n + b, and pack the bits
into []uint64: word i / 64, bit i % 64.
Keep it in bits, not []bool. A []bool would spend a whole byte on one bit and
make the comparison with the list unfair in your favour.
Two more trivial counters — Bytes and Cells — are needed in step 8, when you
measure the matrix.
Your job
graph.go (in the panel) has grown: Degrees, DFS, DFSRecursive,
Components and AdjMatrix have been added, each with
panic("not implemented").
BFSin the panel still shows its holes — the panel shows the skeleton, not your file. In your copy they are already filled in; leave them that way.
Read the contracts, not only the signatures. The doc comments spell out everything the test will check.
graph_test.go has grown too:
| test | what it requires |
|---|---|
TestDFSReproducesTheTable |
0 → 6: path [0 2 3 4 5 6], 12 edges |
TestDFSRecursiveReproducesTheTable |
0 → 6: path [0 1 6], 3 edges |
TestDFSFindsAPathButNotTheShortest |
DFS's path is real, never shorter, and sometimes longer |
TestBothSearchesAgreeOnReachability |
all three agree on WHAT is reachable |
TestTheTwoDFSVersionsDisagreeOnPaths |
the two DFS versions find different paths |
TestComponentsPartitionTheGraph |
the components cover every node |
TestDegreesOnTheTableGraph |
on the lesson's graph: mean 2.00, median 2, max 3 |
TestMatrixAgreesWithList |
both representations describe the same graph |
The test that checks BFS compares against independently computed distances —
a separate bfsDistances function in the test file, not against your own BFS's
answer. Checking an algorithm with itself is checking nothing.
TestDFSFindsAPathButNotTheShortest and TestTheTwoDFSVersionsDisagreeOnPaths
again demand that something is not the case — a shape familiar since lessons
7–13. "Fix" DFS so that it returns shortest paths and you have written BFS with
extra steps, and the test says exactly that:
DFS found the shortest path every time — that is BFS, not DFS
Run go test ./.... It stops at the first unfinished skeleton with
panic: not implemented, so write one function at a time and check it on its
own:
$ go test -run 'DFS' ./...
When it does not pass
found=true path=[0 1 6], 6 edges looked at, when[0 2 3 4 5 6]and 12 were wanted — you took from the front, not the back. That is not DFS — it is BFS. The next test says the same thing in words you have already seen.found=false path=[], 14 edges looked at(DFSRecursive) — you make the recursive call but do not pass its result upwards. The callDFSRecursive(w)must returntrue, and you must return it onwards.fatal error: stack overflow— the recursion never stops: you forgot to mark the node seen, and the ring in the graph spins round until the 1 GB stack limit.Degrees() = 2.00, 3, 3; want 2.00, 2, 3— the median is wrong. It is the middle value of the sorted degrees, not the mean and not the largest.
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 1 is about
making them agree.