ITPEC FE Subject B October 2024 Question 9
From the answer group below, select the correct answer to be inserted into blank in the description. Here, the array indexes start at 1.
The procedure traverse traces through a vertex of the graph shown in the Figure, and outputs all vertex numbers in the graph. The vertex number of the graph is specified with the argument k. The global variable n indicates the number of vertices in the graph. The global array graph represents the graph in the figure. Each element graph[i][j] is equal to 1 if an edge exists between vertices i and j, and it is equal to 0 otherwise. The global array visited stores boolean values, where visited[i] indicates whether vertex i of the graph has been visited during the procedure.
When the procedure is called as traverse(, the output is in the order blank.
Figure Structure of the graph
Answer group
Explanation
1, 2, 3, 5, 4 — depth-first: each call moves to its lowest-numbered unvisited neighbour and returns only when it has none left.
The matrix gives the edges 1–2, 1–4, 2–3, 2–5 and 4–5.
traverse(outputs 1; its first unvisited neighbour is 21) traverse(outputs 2; 1 is visited, so it calls2) traverse(3) traverse(outputs 3; its only neighbour 2 is visited, so it returns3) - Back in
traverse(,2) graph[2][4]is 0 andgraph[2][5]is 1, so it callstraverse(, which outputs 55) - In
traverse(, 2 is visited and 4 is not, so5) traverse(outputs 4; when the calls return, the loop in4) traverse(finds 4 already visited1)
Answer (b)
Why not others:
- •(a) — plain ascending order; 4 cannot follow 3, because 3's only neighbour is 2 and the search backs up to 2, whose next neighbour is 5
- •(c) — breadth-first order (the neighbours of 1, then those of 2); the recursion goes deep before wide, so 3 is output before 4
- •(d) — 4 is not a neighbour of 2, so it cannot come straight after 2; depth-first reaches 3 right after 2
Key rule: A recursive traversal with a visited array is depth-first: it finishes one branch completely before trying the next neighbour, taking neighbours in index order.
Graph Traversal · AI-written, may contain errors
This question comes from an official ITPEC past paper. ITPEC Practice is an independent study tool and is not affiliated with ITPEC. See the official FE past-paper collection or Report an issue.