Graph Fundamentals and Traversals

Lesson 16 of 20

Build an adjacency dict, then watch BFS ripple across it hop by hop while DFS dives deep — same graph, opposite orders.

The big picture

The big picture

A graph is the shape of every network — servers, friendships, maps. One dict stores it; two traversals walk it in two very different ways.

Nodes + edges

Six servers and seven links are already a graph. Traversing it = visiting every dot through the lines, each at most once.

The adjacency dict

graph["S"] = ["A", "B"] reads: S links straight to A and B. Space grows with V + E — here 6 + 7 = 13 list entries.

BFS — the ripple

A deque drives it: the source first, then everything 1 hop out, then 2. First discovery = shortest hop count, guaranteed.

DFS — the dive

Recursion drives it: follow one edge to the end, backtrack, repeat. The call stack remembers the path for free.

Same price tag

Both cost O(V + E): each node dequeued or called once, each edge scanned once — 13 units of work on this graph.