Graph Fundamentals and Traversals

Lesson 16 of 20

Watch BFS flood a five-server network in hops — then send DFS diving down one cable at a time.

The big picture

Graphs everywhere

A graph is the shape of every network — servers, friendships, road maps. Two traversals, BFS and DFS, walk it in two very different ways.

Nodes + edges

Dots and the lines joining them. Five servers and five cables already make a graph you can traverse.

Adjacency list

One vector of neighbors per node: adj[0] = {1, 2} means node 0 plugs into 1 and 2. Space cost: O(V + E).

BFS — the ripple

A queue drives it: visit the source, then everything 1 hop away, then 2. Nearest first, so hop counts come out shortest.

DFS — the dive

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

Same price

Both touch every node and edge at most once: O(V + E). Same visit set, very different order.