Theory

One hop against 214

In step 1 you wrote down a guess: how much longer will DFS's path be?

$ algo gen -n 1000 -seed 3
$ algo net
nodes 1000, edges 744
  degree: mean 1.49, median 1, max 10
  components 446, largest 555 (55.5% of the library)

  path from 0 to 705

                             hops edges looked at         time
  BFS (queue)                   1              5           0s
  DFS (stack)                 214           1251           0s
  DFS (recursive)               1              5            -

  DFS path is 214.0x longer than the shortest

One hop against 214

Book 705 is a direct neighbour of book 0. One edge. BFS finds it after looking at five edges.

DFS walks through 214 books to reach the one that was next door all along.

The reason is visible in step 2. DFS pushes all the neighbours and then takes the last one. If book 705 went in first, it waits at the bottom of the stack until everything above it has been explored — and that was an entire 214-book trail.

It is still found. The path is real. It is just not an answer to the question "in how many hops".

But one case is an anecdote

So the command checks every reachable destination:

  every reachable destination from 0 (554 of them):
    DFS found the shortest path   20 (3.6%)
    DFS found a longer path       534 (96.4%)
    mean DFS/BFS hop ratio        26.45x
    worst case                    214 hops vs 1 (214.0x)

DFS is wrong 96.4% of the time, and on average its path is 26 times longer.

That is not "occasionally unlucky". It is nearly always, and it is not a bug — DFS never promised a shortest path. It is only wrong if you asked for one.

Why BFS can promise

A queue visits in layers: everything one hop away, then everything two hops away.

When to first appears, every shorter layer is already exhausted — if a path had been there, it would have been found earlier. So the first find is the shortest.

A stack has no layers. It goes deep until it hits a dead end and only then backs up — so the first find is simply first, not best.

BFS answers "in how many hops". DFS answers "is it reachable at all". BFS answers the second question too, but DFS is cheaper in memory for it.

And one more line in the table

  components 446, largest 555 (55.5% of the library)

The library network is not one piece. From book 0, 555 books are reachable — 55.5% of the collection; the remaining 445 form 445 more islands, mostly single books nobody ever borrowed alongside another.

That is BFS's work too: Components starts a search from every node not yet reached. Every node is visited exactly once across the whole process, so the cost stays O(V + E) — not V separate searches.