Graph Fundamentals and Traversals
Lesson 16 of 20Six stops, six walkways: BFS sweeps the graph in waves from A while DFS dives corridor-deep — adjacency lists included.
Graphs in one screen
A graph is the least pretentious data structure: dots and lines. Everything from metro maps to your friends list is one — and two traversals unlock it all.
Vertices + edges
Six campus stops joined by six walkways. Any “things connected to things” — friends, flights, web links — is a graph.
The adjacency list
adj.get(u) lists u’s neighbors — List<List<Integer>> in Java. Six lists, one per vertex, O(V + E) memory.
Degree math
A vertex’s degree is its neighbor count. All degrees sum to 2 × edges: 12 here means exactly 6 edges.
BFS: the wave
A queue sweeps outward layer by layer from the source — hop counts come out shortest in unweighted graphs.
DFS: the dive
A stack (or recursion) follows one corridor to its end, then backtracks to the last fork.
Euler bridges Königsberg
A puzzle about seven bridges becomes vertices and edges on paper — the first graph.
Moore exits the maze
Edward F. Moore uses a queue to explore a maze in rings — breadth-first search is born.
Tarjan goes deep
Depth-first search becomes a machine for cycles, bridges and connected components.
Graphs everywhere
Social feeds, GPS routing, web crawling and garbage collectors all traverse graphs.
BFS wavefront
A queue sweeps the graph in rings: every node enters at the smallest possible hop count.
BFS from A — a queue drives the sweep. A starts in the queue at hop 0.
How BFS runs
Four moves on repeat — the queue turns a tangle of edges into neat layers.
Walkthrough
BFS on an adjacency list in real Java — then the degree sum rule, counted the easy way.
1import java.util.ArrayDeque;2import java.util.List;3import java.util.Queue;45public class Bfs {6public static void main(String[] args) {7List<List<Integer>> adj = List.of(8List.of(1, 2), List.of(0, 3), List.of(0, 3, 4),9List.of(1, 2, 5), List.of(2), List.of(3));10boolean[] seen = new boolean[6];11Queue<Integer> queue = new ArrayDeque<>();12queue.add(0);13seen[0] = true;14while (!queue.isEmpty()) {15int curr = queue.remove();16System.out.print((char) ('A' + curr) + " ");17for (int next : adj.get(curr)) {18if (!seen[next]) {19seen[next] = true;20queue.add(next);21}22}23}24}25}
adj holds one neighbor list per vertex: A→[1, 2], B→[0, 3], C→[0, 3, 4], D→[1, 2, 5], E→[2], F→[3].
DFS goes deep
Same graph, opposite personality: DFS follows one corridor to its end, then backtracks.
Same graph, new rule: DFS dives deep before wide — a stack replaces BFS’s queue.
Predict the output
A four-node graph, one BFS — how many hops to the far node?
1import java.util.ArrayDeque;2import java.util.Queue;34public class Predict {5public static void main(String[] args) {6int[][] adj = {{1, 2}, {3}, {3}, {}};7int[] dist = new int[4];8Queue<Integer> q = new ArrayDeque<>();9q.add(0);10boolean[] seen = {true, false, false, false};11while (!q.isEmpty()) {12int curr = q.remove();13for (int next : adj[curr])14if (!seen[next]) { seen[next] = true; dist[next] = dist[curr] + 1; q.add(next); }15}16System.out.println(dist[3] + " hops to D");17}18}
Hint: BFS stamps dist[curr] + 1 the moment a node is discovered. A’s wave reaches D through B or C — count the rings.
Concept check
Click a term, then click its meaning to lock the pair.
Key takeaways
A graph is vertices plus edges — adjacency lists store neighbors in List<List<Integer>>.
Degrees always sum to 2 × edges (the handshake rule): 12 here means exactly 6 edges.
BFS uses a queue and visits in layers — its hop counts are the shortest distances.
Mark nodes seen when they ENQUEUE, not when they dequeue — that kills duplicates.
DFS uses a stack (or recursion) and dives deep before backtracking.
Both traversals cost O(V + E) — every vertex once, every edge once.