Graph Fundamentals and Traversals
Lesson 16 of 20Build an adjacency dict, then watch BFS ripple across it hop by hop while DFS dives deep — same graph, opposite orders.
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.
BFS wavefront
A deque drives the wavefront: dequeued nodes go amber, then green with their links — hop counts fill in order.
Six servers, seven links. BFS starts at hub S: dist[S] = 0 and the queue holds just [S]. Everything else is undiscovered.
BFS control flow
One deque, one membership test — that is all BFS is.
deque vs recursion
BFS with collections.deque and hop counts — then recursive DFS over the very same network.
1from collections import deque2graph = {3'S': ['A', 'B'],4'A': ['S', 'C'],5'B': ['S', 'C'],6'C': ['A', 'B', 'D'],7'D': ['C'],8}9dist = {'S': 0}10order = []11queue = deque(['S'])1213while queue:14node = queue.popleft()15order.append(node)16for nxt in graph[node]:17if nxt not in dist:18dist[nxt] = dist[node] + 119queue.append(nxt)2021print(' '.join(order), '| D is', dist['D'], 'hops from S')
The adjacency dict: every key maps to the list of its direct neighbors. S plugs into A and B.
DFS dive
Same six servers, same links — but DFS pushes deep down one path before it even glances at the rest.
Same network as the BFS wavefront. DFS asks a different question: how deep can one path go? dfs(S) is about to open.
Predict the output
A tiny BFS with a list-queue — hops dict does double duty.
1graph = {'A': ['B', 'C'], 'B': ['D'], 'C': ['D'], 'D': []}2hops = {'A': 0}3queue = ['A']4while queue:5node = queue.pop(0)6for nxt in graph[node]:7if nxt not in hops:8hops[nxt] = hops[node] + 19queue.append(nxt)10print(len(hops), hops['D'])11print(max(hops.values()))
Hint: hops doubles as the visited set — its keys are exactly the discovered nodes. D is first reached from B at hop 2; C cannot improve it.
Concept check
Click a term, then click its meaning to lock the pair.
Key takeaways
A graph is just an adjacency dict: keys are nodes, values are direct-neighbor lists — O(V + E) space.
BFS uses collections.deque: popleft() from the front, append() at the back — strict FIFO.
A node’s first discovery in BFS is its shortest hop count — dist fills in wavefront order.
DFS recurses: mark seen, visit, dive into each unseen neighbor, backtrack when stuck.
Both traversals cost O(V + E) — every node dequeued once, every edge scanned once.
A missing dict key means "never seen" — the O(1) membership test replaces a separate visited list.