Chapter 5: Graph Traversal
Multiple Choice · Representation
Question 1: List and Matrix Size
An undirected graph with 7 vertices and 9 edges is stored both as adjacency lists and as an adjacency matrix. What are the total number of entries in the adjacency lists and the number of cells in the matrix?
C: In an undirected graph every edge appears in two lists: 2E = 18 entries; the matrix has V × V = 49 cells. A forgets that an undirected edge is written twice; B leaves out the diagonal (n(n−1)). Memory: list O(V + E), matrix O(V²).
Output Question · Representation
Question 2: DFS on a Matrix
A directed graph is given by its adjacency matrix (G[i][j] = 1 means an edge i → j). What does dfs(0) print?
| 0 | 1 | 2 | 3 | 4 | |
|---|---|---|---|---|---|
| 0 | 0 | 0 | 1 | 0 | 1 |
| 1 | 1 | 0 | 0 | 0 | 0 |
| 2 | 0 | 1 | 0 | 1 | 0 |
| 3 | 0 | 1 | 0 | 0 | 0 |
| 4 | 0 | 0 | 0 | 1 | 0 |
void dfs(int v) { visited[v] = true; System.out.print(v + " "); for (int w = 0; w < n; w++) if (G[v][w] == 1 && !visited[w]) dfs(w); }
Show answer
Output: 0 2 1 3 4
- Row 0: the first 1 is in column 2 → dfs(2). Row 2: 1 → dfs(1); the only neighbor of 1, vertex 0, is visited, so it returns.
- Continuing the scan in row 2: 3 → dfs(3); 3 → 1 is visited, so it returns. 2 finishes, back to 0.
- In row 0, column 4 → dfs(4); 4 → 3 is visited. The calls end.
Rows are scanned left to right, so neighbors are tried in increasing order. Scanning a row of n entries for every vertex makes the time O(V²) (the BFS order would be 0 2 4 1 3).
Step-by-Step Trace · DFS
Question 3: Tracing Recursive DFS
dfs(0, visited) prints the vertices in which order? Yellow vertices are the frames on the call stack.
Directed graph, adjacency lists in increasing order: 0: 1, 3 · 1: 2, 4 · 2: 0 · 3: 4 · 4: 2, 5 · 5: —. No vertex has been visited yet.
dfs(0): 0 is marked and printed; there is a single frame on the call stack.
0's neighbor 1 is unvisited → dfs(1): marked and printed; a new frame is pushed onto the stack.
1's neighbor 2 is unvisited → dfs(2): marked and printed; a new frame is pushed onto the stack.
Edge 2 → 0: 0 is already visited (on the stack, still in progress) → skipped.
2 is done and its call returns; control goes back to 1 (backtracking).
1's neighbor 4 is unvisited → dfs(4): marked and printed; a new frame is pushed onto the stack.
Edge 4 → 2: 2 is already visited (finished) → skipped.
4's neighbor 5 is unvisited → dfs(5): marked and printed; a new frame is pushed onto the stack.
5, 4 and 1 are done and their calls return; control goes back to 0 (backtracking).
0's neighbor 3 is unvisited → dfs(3): marked and printed; a new frame is pushed onto the stack.
Edge 3 → 4: 4 is already visited (finished) → skipped.
3 is done and its call returns; control goes back to 0 (backtracking).
All calls have returned. Output: 0 1 2 4 5 3. The highlighted edges form the DFS tree; 2 → 0 is a back edge (a cycle).
void dfs(int v, boolean[] visited) { visited[v] = true; System.out.print(v + " "); for (int w : adj[v]) if (!visited[w]) dfs(w, visited); }
Multiple Choice · DFS
Question 4: Properties of Stack-Based DFS
Which of the following is true for the dfsStack method written in the lectures (the version that marks vertices when popping them off the stack)?
B: Since marking happens at pop time, a vertex that has not been popped yet can be pushed again from different neighbors; the number of pushes is 1 + Σ degree, i.e. O(E). C is wrong: the order is reversed relative to the push order. D is wrong: without a visited array, a cycle makes the same vertices be pushed forever.
Multiple Choice · DFS
Question 5: A Cycle in a Directed Graph
A cycle is being searched for with DFS in a directed graph (yellow: on the call stack, dark: finished, white: undiscovered). Which situation during the DFS shows for certain that there is a cycle?
C: A vertex w on the stack is an ancestor of v; the tree path w ⇝ v and the edge v → w together form a cycle (a back edge). A and B are wrong: in a directed graph, an edge to a finished vertex (a cross or forward edge) need not create a cycle. In the figure the edge d → b will be examined later; since b is on the stack, the cycle e → d → b → c → e is found.
Output Question · DFS
Question 6: How Many Times Is It Started?
The code below is run on a directed graph (dfs is recursive DFS). What does it print? What would it print if the loop ran from v = n − 1 down to 0?
int count = 0; for (int v = 0; v < n; v++) if (!visited[v]) { dfs(v, visited); count++; } System.out.println(count);
Show answer
Increasing order: 5. dfs(0) visits only {0, 1} (there is no edge from 0 to 2); then 2, 3, 4, 5 are started separately.
Decreasing order: 2. dfs(5) visits {5, 4}, and dfs(3) visits the remaining four vertices via 3 → 2 → 0 → 1.
In an undirected graph, the number of starts equals the number of connected components. In a directed graph, however, it depends on the order; it gives neither the number of weak components (2) nor the number of strongly connected components (6).
Step-by-Step Trace · BFS
Question 7: Tracing BFS
bfs(0) prints the vertices in which order? Trace the queue contents and the BFS tree.
Undirected graph, adjacency lists in increasing order. 0 was marked and enqueued (layer 0).
0 was dequeued and printed. The new neighbors 3, 5 were marked and added to the end of the queue (distance 1).
3 was dequeued and printed. The new neighbors 1, 6 were marked and added to the end of the queue (distance 2).
5 was dequeued and printed. The new neighbor 2 was marked and added to the end of the queue (distance 2).
1 was dequeued and printed. It has no undiscovered neighbors.
6 was dequeued and printed. The new neighbor 4 was marked and added to the end of the queue (distance 3).
2 was dequeued and printed. It has no undiscovered neighbors.
4 was dequeued and printed. It has no undiscovered neighbors.
The queue is empty. Output 0 3 5 1 6 2 4; layers {0}, {3, 5}, {1, 6, 2}, {4}. The highlighted edges form the BFS tree.
void bfs(int s) { boolean[] visited = new boolean[n]; Queue<Integer> queue = new LinkedList<>(); visited[s] = true; queue.add(s); while (!queue.isEmpty()) { int v = queue.poll(); System.out.print(v + " "); for (int w : adj[v]) if (!visited[w]) { visited[w] = true; queue.add(w); } } }
Output Question · BFS
Question 8: BFS Distances and Path
Run BFS from A (neighbors in alphabetical order) and find the visit order, the distance and the parent of each vertex. Using the parent array, what is the shortest path from A to H?
Show answer
Order: A B D C E G F H
| vertex | A | B | C | D | E | F | G | H |
|---|---|---|---|---|---|---|---|---|
| dist | 0 | 1 | 2 | 1 | 2 | 3 | 2 | 3 |
| parent | — | A | B | A | B | C | D | G |
H → parent G → parent D → parent A; reversed, A → D → G → H (3 edges). A–B–C–F–H is also a path but has 4 edges; the moment BFS first reaches a vertex, it has found a path with the fewest edges.
Multiple Choice · BFS
Question 9: BFS on a Weighted Graph
A path from s to t is found by BFS using the parent array (neighbors in alphabetical order). What are the total weight of the path found and the weight of the true shortest path?
D: BFS counts edges; it finds t as a neighbor of s in the first layer: s → t (1 edge, weight 7). The lightest path is s → a → t = 2 + 2 = 4. B takes s → b → t (6) to be the shortest. A weighted graph needs Dijkstra; BFS is correct only when all weights are equal.
Multiple Choice · BFS
Question 10: Queue and Stack Size
A complete binary tree with 15 vertices (4 levels) is traversed from the root as a graph. In the BFS from the lectures, what is the maximum number of vertices the queue holds, and in recursive DFS, what is the maximum number of frames on the call stack?
B: BFS keeps the 8 leaves of the last level in the queue together (the widest layer); DFS goes as deep as the longest root-to-leaf path, 4 frames. A mixes the two up. In general, BFS memory depends on the widest layer and DFS memory on the deepest path; both are O(V) in the worst case.
Classic Question · BFS
Question 11: The Bipartite Test
Use BFS from A to find the layers, and color the even layers one color and the odd layers the other. Is the graph bipartite? If not, which edge shows the problem, and what happens if the edge D–E is deleted?
Show answer
Layers: A (0); B, C (1); D, E (2); F (3). D–E has both endpoints in layer 2 → same color: the graph is not bipartite. C–D–E is a cycle of odd length (3).
If D–E is deleted, all edges join consecutive layers: the classes are {A, D, E} and {B, C, F}; the graph becomes bipartite. The test takes O(V + E).
Multiple Choice · Tarjan SCC
Question 12: How Many SCCs?
How many strongly connected components (SCCs) does the directed graph have?
D: {0, 1, 2} (0 → 1 → 2 → 0), {3, 4} (3 ⇄ 4) and {5, 6, 7} (5 → 6 → 7 → 5). The edges 1 → 6, 2 → 3 and 4 → 5 connect the components but do not merge them, since there is no path back. The answer 1 is the misconception “everything is reachable from 0”: an SCC requires mutual reachability.
Step-by-Step Trace · Tarjan SCC
Question 13: Tracing Tarjan
scc(0) prints what? Trace index, low and the stack.
Graph: 0 ⇄ 1, 1 → 2, 2 → 3 → 4 → 2. index[w] == 0 means unvisited; the label next to a vertex is index/low.
scc(0): index = low = 1; 0 is pushed onto the stack.
0 → 1: 1 is unvisited → scc(1): index = low = 2; pushed onto the stack.
1 → 0: 0 is on the stack → low[1] = min(2, index[0] = 1) = 1.
1 → 2: 2 is unvisited → scc(2): index = low = 3; pushed onto the stack.
2 → 3: 3 is unvisited → scc(3): index = low = 4; pushed onto the stack.
3 → 4: 4 is unvisited → scc(4): index = low = 5; pushed onto the stack.
4 → 2: 2 is on the stack → low[4] = min(5, index[2] = 3) = 3.
low[4] = 3 ≠ index[4] = 5 → 4 is not a root and stays on the stack.
scc(4) returned: low[3] = min(4, low[4] = 3) = 3. low[3] = 3 ≠ index[3] = 4 → 3 is not a root and stays on the stack.
scc(3) returned: low[2] = min(3, low[3] = 3) = 3. low[2] = index[2] = 3 → 2 is a root; 4, 3, 2 are popped and printed: SCC {2, 3, 4}.
scc(2) returned: low[1] = min(1, low[2] = 3) = 1. low[1] = 1 ≠ index[1] = 2 → 1 is not a root and stays on the stack.
scc(1) returned: low[0] = min(1, low[1] = 1) = 1. low[0] = index[0] = 1 → 0 is a root; 1, 0 are popped and printed: SCC {0, 1}.
Done: {2, 3, 4} was found first, then {0, 1}. SCCs come out in reverse topological order: there is an edge {0, 1} → {2, 3, 4}.
void scc(int v) { index[v] = low[v] = ++counter; stack.push(v); onStack[v] = true; for (int w : adj[v]) { if (index[w] == 0) { scc(w); low[v] = Math.min(low[v], low[w]); } else if (onStack[w]) low[v] = Math.min(low[v], index[w]); } if (low[v] == index[v]) { int w; do { w = stack.pop(); onStack[w] = false; System.out.print(w + " "); } while (w != v); System.out.println(); } }
Output Question · Tarjan SCC
Question 14: The On-Stack Check
In the Tarjan code, if the line else if (onStack[w]) is changed to just else (so that for every visited w, low[v] = min(low[v], index[w]) is executed), what does a program print that calls scc from each unvisited vertex in the order 0, 1, 2, 3? What would the correct code print?
Show answer
Correct code: 1 0 and 3 2 (two lines).
Faulty code: only 1 0. In scc(2), index[2] = 3; in scc(3), index[3] = 4; the edge 3 → 2 makes low[3] equal to 3. On the edge 3 → 0, however, vertex 0 is in a finished SCC, but since the check is gone, low[3] = index[0] = 1. On return, low[2] = 1 ≠ 3 → 2 is not counted as a root; {2, 3} is never printed and stays on the stack.
Edges to finished SCCs must be ignored; otherwise roots are lost.
Output Question · Applications
Question 15: Reverse Finishing Order
In a directed acyclic graph (DAG) the adjacency lists are in increasing order. What does the program print?
void dfsFinish(int v) { visited[v] = true; for (int w : adj[v]) if (!visited[w]) dfsFinish(w); stack.push(v); // push when done } // main: for every unvisited v for (int v = 0; v < n; v++) if (!visited[v]) dfsFinish(v); while (!stack.isEmpty()) System.out.print(stack.pop() + " ");
Show answer
Finishing order: 4, 3, 1, 2, 0, 5 (dfsFinish(0): 0 → 1 → 3 → 4; 4, 3, 1 finish; 2 finishes, 0 finishes; then dfsFinish(5): 5 finishes).
Order popped from the stack (reverse finishing): 5 0 2 1 3 4
For every edge u → v, v finishes before u; therefore u comes first in the reverse finishing order. Kahn gives 0 5 1 2 3 4 on this graph; both are valid. Time O(V + E).
Step-by-Step Trace · Applications
Question 16: Tracing Kahn's Algorithm
kahn() prints which topological order? Trace the in-degrees and the queue.
DAG edges: 0→2, 0→3, 1→3, 1→4, 3→2, 2→5, 4→5; in-degrees as labeled.
In-degree 0 vertices (0, 1) are enqueued.
Dequeue and print 0; in-degree 2→1, 3→1; nothing enqueued.
Dequeue and print 1; in-degree 3→0, 4→0; enqueue 3 and 4.
Dequeue and print 3; in-degree 2→0; enqueue 2.
Dequeue and print 4; in-degree 5→1; nothing enqueued.
Dequeue and print 2; in-degree 5→0; enqueue 5.
Dequeue and print 5; no outgoing edges.
Queue empty, all 6 vertices out → acyclic. Topological order: 0 1 3 4 2 5.
void kahn() { int[] indeg = new int[n]; // in-degrees for (int v = 0; v < n; v++) for (int w : adj[v]) indeg[w]++; Queue<Integer> queue = new LinkedList<>(); for (int v = 0; v < n; v++) if (indeg[v] == 0) queue.add(v); while (!queue.isEmpty()) { int v = queue.poll(); System.out.print(v + " "); for (int w : adj[v]) if (--indeg[w] == 0) queue.add(w); } }
Multiple Choice · Applications
Question 17: An Invalid Topological Order
For the DAG in the figure, which of the following is not a topological order?
A: There is an edge 3 → 2; in a topological order 3 must come before 2. In A, 2 is written before 3. The other three write u first for every edge u → v; the topological order is not unique (depending on the queue order, Kahn gives one of these, 0 1 3 4 2 5).
Multiple Choice · Applications
Question 18: The Bridge Condition
DFS is run on an undirected graph; disc(v) is the discovery order, and low(w) is the smallest discovery value reachable from the subtree of w using a single back edge. When is the DFS-tree edge v–w (w a child) a bridge?
B: If there is no back edge from the subtree of w to v or to an ancestor of v, deleting v–w disconnects the subtree. A (≥) is the articulation point condition: if the subtree can return to v, v–w is not a bridge, but v can still be an articulation point. D only says that w was discovered right after v.