algoritmauzmanı
Sign in
TREN
8.4Exam Practice
Lesson 8.4.1

Graphs: exam questions and answers

This page is the exam practice for the graphs section. University exams ask about graphs in a few recurring ways: degree and edge-count formulas, drawing or reading an adjacency matrix and adjacency lists, writing BFS and DFS orders, telling whether an order is valid, counting components, finding a topological order and a cycle, working out shortest paths, writing short functions and comparing the two layouts. Here you get original questions of each kind with step-by-step answers.

What you will learn
  • How to read formulas such as the degree sum and the largest edge count, and both layouts, quickly
  • How to trace BFS and DFS orders, components, topological order, cycles and shortest paths by hand
  • How to write short functions such as counting edges, checking symmetry and finding the in-degree, and give their cost
30 min

1Terms and formulas

The questions are original, but their types were picked from the kinds that often appear in published midterm and final exams, homework and exercise sheets of universities in Turkey and abroad. Solve each question yourself first, then open the box and compare. Unless stated otherwise, neighbours are visited from the smallest number to the largest; exams break ties the same way or alphabetically. The names in the code match the adjacency matrix and adjacency list lessons.

0132456
Graph A: 7 vertices, 9 edges, undirected. Questions 1, 7, 8, 9, 10 and 14 use this graph.
1Give the degree of every vertex in graph A. What is the sum of the degrees, and how is it related to the number of edges?Midterm · concept

In an undirected graph the degree of a vertex is the number of edges touching it. Count the neighbours one by one:

VertexNeighboursDegree
01, 2, 43
10, 32
20, 4, 53
31, 62
40, 2, 53
52, 4, 63
63, 52

The total is 3 + 2 + 3 + 2 + 3 + 3 + 2 = 18; there are 9 edges. Each edge is counted once in the degree of each of its two ends, so in every undirected graph the sum of the degrees = 2 × the number of edges (the handshake rule). In a directed graph the sum of the in-degrees and the sum of the out-degrees are each equal to the number of edges.

2How many edges can a graph with 10 vertices have at most, with no self-loops and no repeated edges? Answer for an undirected and a directed graph. How many edges does a connected undirected graph with 10 vertices have at least?Midterm · concept
  • Undirected: each pair of vertices is joined by at most one edge. The number of pairs is n(n-1)/2 = 10 × 9 / 2 = 45. This graph, where every pair is joined, is called the complete graph (K10).
  • Directed: every ordered pair (u, v) is a separate edge: n(n-1) = 10 × 9 = 90.
  • Connected, at least: n - 1 = 9 edges. A connected graph with 9 edges has no cycle, so it is a tree; with one edge fewer the graph splits into two pieces.

These bounds also appear in complexity answers: E can be at most O(V²), so O(V + E) is O(V²) in the worst case.

3Can a simple undirected graph with 5 vertices (no self-loops, no repeated edges) have the degrees 3, 3, 2, 2, 1? What about 3, 3, 2, 2, 2?Final · concept

The sum of the degrees is twice the number of edges, so it is always even. 3 + 3 + 2 + 2 + 1 = 11 is odd: no such graph exists. For the same reason, every graph has an even number of vertices with odd degree; here there are three.

3 + 3 + 2 + 2 + 2 = 12 is even, which means 6 edges. An even sum is needed but is not enough on its own; you show it by drawing an example. Call the vertices a, b, c, d, e: a-b, a-c, a-d, b-c, b-e, d-e. The degrees are a: 3, b: 3, c: 2, d: 2, e: 2. Such a graph exists.

2Matrix and list layouts

01324
Graph D: 5 vertices, 7 edges, directed. Question 4 uses this graph.
4Write the adjacency matrix and the adjacency lists of graph D. Find the in-degree and out-degree of every vertex.Midterm · trace

In the matrix adj[u][v] = 1 means there is an edge from u to v. The row is the vertex the edge leaves, the column the vertex it enters. The graph is directed, so the matrix is not symmetric.

01234
001010
100100
210000
300101
401000

The lists hold only the outgoing edges of each vertex, in order: 0: 1 → 3, 1: 2, 2: 0, 3: 2 → 4, 4: 1. There are 7 list nodes in all, one per edge.

VertexOut (row sum)In (column sum)
021
112
212
321
411
Total77

Both totals equal the number of edges, 7. In the matrix the out-degree is a row sum and the in-degree a column sum; with lists the out-degree is the length of a list, while the in-degree needs every list to be read (Question 18).

5Below is the adjacency matrix of a graph. Is the graph directed or undirected? How many edges does it have, what is the degree of 1, and does it have a cycle?Midterm · concept

The matrix:

0123
00110
11011
21100
30100
  • Every adj[i][j] = adj[j][i]: the matrix is symmetric, so the graph is read as undirected. The diagonal is 0, so there are no self-loops.
  • There are 8 ones in the matrix. In an undirected graph each edge sits in two cells: 8 / 2 = 4 edges (0-1, 0-2, 1-2, 1-3).
  • The row of 1 has three ones: degree 3.
  • 0-1-2-0 is a cycle. 3 is joined only to 1; its degree is 1.
6An undirected graph has 1000 vertices and 3000 edges. How much room do an adjacency matrix and adjacency lists take? Which one do you choose? When is the other one better?Final · comparison
  • Matrix: V × V = 1000 × 1000 = 1,000,000 cells. Only 6000 of them are 1; the rest are wasted.
  • Lists: 1000 head pointers, and since each edge sits in two lists, 2 × 3000 = 6000 nodes. O(V + E) in total, a few thousand units.

This graph is sparse (E is much smaller than V²), so you choose lists. For dense graphs, where the number of edges gets close to V², or when "are u and v neighbours?" is asked very often, the matrix is better: it answers that question in O(1) and carries no pointers. More in Matrix or lists?

3Tracing BFS and DFS

7Write the visiting order of a BFS on graph A starting at 0. Show the contents of the queue after every step.Midterm · trace

The vertex taken out of the queue is written, and its unmarked neighbours go to the back of the queue from small to large and are marked at once.

Taken outAddedQueue (front on the left)
01, 2, 41 2 4
132 4 3
254 3 5
4none (0, 2, 5 marked)3 5
365 6
5none6
6noneempty

BFS order: 0 1 2 4 3 5 6. The levels: 0; then 1, 2, 4; then 3, 5; then 6. More in BFS.

8Write the visiting order of a recursive DFS on the same graph, starting at 0.Midterm · trace

DFS goes down to the first unmarked neighbour at once, and steps back when no neighbours are left.

  1. 0 → first neighbour 1.
  2. 1 → 0 is marked, go down to 3.
  3. 3 → 1 is marked, go down to 6.
  4. 6 → 3 is marked, go down to 5.
  5. 5 → go down to 2 (4 is unmarked too, but 2 is smaller).
  6. 2 → 0 is marked, go down to 4.
  7. 4 → its neighbours 0, 2 and 5 are marked; step back. All the calls return one by one.

DFS order: 0 1 3 6 5 2 4. At the deepest point the call stack holds 0, 1, 3, 6, 5, 2, 4: seven frames. More in DFS.

9The function below is called as dfsStack(g, 0) on the adjacency lists of graph A. What does it print? Why is the result different from the recursive DFS?Final · code reading
void dfsStack(struct Graph* g, int start) {    bool visited[MAX] = {false};    int stack[MAX * MAX], top = -1;    stack[++top] = start;    while (top >= 0) {        int u = stack[top--];        if (visited[u]) continue;        visited[u] = true;        printf("%d ", u);        for (struct Node* p = g->adj[u]; p != NULL; p = p->next)            if (!visited[p->data]) stack[++top] = p->data;    }}

The unmarked vertex popped from the stack is printed and its neighbours are pushed from small to large. The stack hands back the last one first, so the largest neighbour comes out first:

PoppedPrintedStack (top on the right)
001 2 4
441 2 2 5
551 2 2 2 6
661 2 2 2 3
331 2 2 2 1
111 2 2 2
221 2 2
2, 2, 1none (marked)empty

Output: 0 4 5 6 3 1 2. This is a valid DFS order too, but it is not the order of the recursive version (0 1 3 6 5 2 4). To get that order, push the neighbours from large to small. Also, the same vertex can enter the stack more than once; that is why the mark is checked when a vertex is popped.

10For a BFS on graph A starting at 0, if the order in which neighbours are visited is not known, which of these can be a valid BFS order? (a) 0 4 2 1 5 3 6 (b) 0 1 2 4 6 3 5 (c) 0 2 1 4 3 5 6Final · trace

BFS follows two rules. Vertices come out in order of distance: first {0}, then {1, 2, 4}, then {3, 5}, then {6}. Also, the vertices of a level come in the order of the vertices that first found them.

  • (a) valid. The first level comes out as 4, 2, 1. The first to find 5 is 4 (taken out first) and the one to find 3 is 1 (taken out last). So 5 comes before 3: 0 4 2 1 5 3 6.
  • (b) invalid. 6 is at distance 3; it cannot come out before 3 and 5, which are at distance 2.
  • (c) invalid. The first level comes out as 2, 1, 4. Since 2 leaves before 1, it puts 5 (a neighbour of 2) into the queue before 3 (a neighbour of 1). The order should have been 0 2 1 4 5 3 6.

4Components, topological order, cycles and shortest paths

11An undirected graph with 9 vertices (0-8) has the edges 0-3, 1-4, 3-6, 4-7, 2-5, 6-0. How many connected components are there? How many edges must be added at least to make the graph connected?Midterm · trace

A DFS is started from every unmarked vertex, and the vertices it reaches form one component:

StartComponent
0{0, 3, 6}
1{1, 4, 7}
2{2, 5}
8{8} (no edges)

There are 4 components. Each new edge joins at most two components, so at least 4 - 1 = 3 edges are needed; for example 0-1, 1-2 and 2-8. 0-3-6-0 is a cycle, but it does not change the number of components. More in Connected components.

012345
Graph T: a DAG (directed acyclic graph) with 6 vertices. Question 12 uses this graph.
12Graph T shows the courses of a department and their prerequisites (u → v: u is taken before v). Find a topological order with Kahn's algorithm (smaller number first on ties in the queue). Are 0 2 4 1 3 5 and 0 1 3 2 4 5 topological orders too? How many topological orders are there in all?Final · trace

In-degrees: 0: 0, 1: 1, 2: 1, 3: 2, 4: 1, 5: 2. A vertex with in-degree 0 joins the queue; the edges of the vertex taken out are removed.

Taken outIn-degrees that dropQueue
01 → 0, 2 → 01 2
13 → 12
23 → 0, 4 → 03 4
35 → 14
45 → 05
5noneempty

Kahn order: 0 1 2 3 4 5. An order is right if u comes before v for every edge u → v. 0 2 4 1 3 5 is right: all seven edges keep the rule. 0 1 3 2 4 5 is wrong: there is an edge 2 → 3, but 3 is written before 2.

To count all the orders: 0 is always first and 5 always last. 1, 2, 3, 4 remain in the middle; the rules are 1 < 3, 2 < 3, 2 < 4. The orders that fit are 1 2 3 4, 1 2 4 3, 2 1 3 4, 2 1 4 3, 2 4 1 3: there are 5 topological orders. More in Topological sort.

01234
Graph Y: 5 vertices, directed. Question 13 uses this graph.
13Use a three-colour DFS starting at 0 to find whether graph Y has a cycle. Which back edge closes the cycle? Why does the edge 4 → 3 not count as a cycle?Final · trace
  1. 0 turns grey; go down to its first neighbour 1; 1 is grey.
  2. 1 → go down to 2; 2 is grey.
  3. 2 → go down to 3; 3 is grey. Path: 0, 1, 2, 3.
  4. The neighbour of 3, 1, is grey: 1 is on the path. 3 → 1 is a back edge, and the cycle 1 → 2 → 3 → 1 is found.

Once the cycle is found, the function returns true at once. Had the search gone on with no cycle: 3, 2 and 1 would turn black and the DFS would go from 0 down to 4. The 3 at the end of the edge 4 → 3 is black: everything below 3 was visited already and there is no path from 3 back to 4. An edge to a black vertex does not close a cycle. More in Detecting a cycle.

14In graph A, find the length of the shortest paths from 6 to every vertex. Write the shortest path from 6 to 0.Midterm · trace

The edges have no weights, so BFS is used. The queue order is 6, 3, 5, 1, 2, 4, 0; every vertex gets its distance and previous vertex the moment it is first seen.

Vertex0123456
Distance3221210
Previous135656-

Read backwards from 0: 0 ← 1 ← 3 ← 6. The path is 6 3 1 0, length 3. 6 5 2 0 also has 3 edges and is a shortest path too; BFS keeps the one it found first. More in Shortest paths.

5Reading and writing code

15What does the function below compute on a graph kept in an adjacency matrix? What does it return for the matrix of Question 5? What is its complexity?Midterm · code reading
int mystery(struct Graph* g) {    int s = 0;    for (int i = 0; i < g->n; i++)        for (int j = i + 1; j < g->n; j++)            if (g->adj[i][j] == 1) s++;    return s;}

The inner loop starts at j = i + 1: it looks only at the cells above the diagonal, that is at each pair of vertices once. In an undirected graph this gives the number of edges. For the matrix of Question 5 there are 4 ones in the upper triangle: the function returns 4.

About n²/2 cells are read whatever the number of edges: O(V²). On a directed graph it gives a wrong answer, because it misses the edges in the lower triangle.

16Write a function that returns the number of edges of a graph kept in adjacency lists. The graph can be directed or undirected.Midterm · code writing

Count the nodes in all the lists. In a directed graph each edge sits in one list; in an undirected graph in two, so the total is halved.

int countEdges(struct Graph* g) {    int total = 0;    for (int u = 0; u < g->n; u++)        for (struct Node* p = g->adj[u]; p != NULL; p = p->next)            total++;                          // each node is one edge end    return g->directed ? total : total / 2;   // undirected: in two lists}

Every list node is read once: O(V + E). With a matrix the same job takes O(V²), as seen in Question 15.

17For a graph kept in an adjacency matrix to be read as undirected, the matrix must be symmetric. Write a function that returns whether the matrix is symmetric.Midterm · code writing

Compare adj[i][j] with adj[j][i] for every pair i, j. The diagonal matches itself and the lower triangle mirrors the upper one, so walking the upper triangle is enough.

bool isSymmetric(struct Graph* g) {    for (int i = 0; i < g->n; i++)        for (int j = i + 1; j < g->n; j++)     // the upper triangle is enough            if (g->adj[i][j] != g->adj[j][i]) return false;    return true;}

In the worst case n(n-1)/2 comparisons: O(V²). It returns false at the first mismatch. For the matrix of graph D the 0-2 cells differ (adj[0][2] = 0, adj[2][0] = 1), so the function returns false.

18Write a function that returns the in-degree of a vertex in a directed graph kept in adjacency lists. What is its complexity? What would you do if you needed the in-degree of every vertex?Final · code writing

The lists hold only the outgoing edges of each vertex. To find the edges coming into v, every list is read and the nodes whose data is v are counted.

int inDegree(struct Graph* g, int v) {    int count = 0;    for (int u = 0; u < g->n; u++)            // every list is read        for (struct Node* p = g->adj[u]; p != NULL; p = p->next)            if (p->data == v) count++;        // an edge u -> v    return count;}

O(V + E) for one vertex. Calling this function for every vertex costs O(V × (V + E)). If you need every in-degree, read the lists once and do indeg[p->data]++ for every node: O(V + E) in total. Kahn's algorithm does exactly this. With a matrix the in-degree is a column sum: O(V).

6Complexity and comparison

19Compare the time of these operations for an adjacency matrix and adjacency lists: are u and v neighbours, visiting all the neighbours of u, adding an edge, walking the whole graph with BFS or DFS. How much memory does each take?Final · comparison
OperationMatrixLists
Are u and v neighbours?O(1)O(deg(u))
Visit the neighbours of uO(V)O(deg(u))
Add an edgeO(1)O(deg(u)) sorted; O(1) at the head
BFS / DFSO(V²)O(V + E)
MemoryO(V²)O(V + E)

The matrix answers the neighbour question in constant time but reads a whole row to find the neighbours of a vertex; BFS and DFS read one row per vertex, so they cost O(V²). The lists read only the edges that exist. Lists suit sparse graphs, the matrix suits dense ones.

20Compare BFS and DFS: which structure do they use, in what order do they visit, which one finds shortest paths, and which one is used for cycles and topological order?Final · comparison
BFSDFS
StructureQueueStack or recursion (call stack)
OrderLevel by level, near to farTo the end of a branch, then back
TimeO(V + E)O(V + E)
Unweighted shortest pathYesNo
Typical usesShortest paths, levels, Kahn's algorithmCycle detection, components, topological order by finish time

Both find the connected components and visit every vertex once. In memory BFS takes as much room as the widest level and DFS as much as the longest path. In a tree their counterparts are level order and preorder traversal.

7Try it

An undirected graph has 12 edges. What is the sum of the degrees?

Show the answer

The answer is B. Each edge is counted once in the degree of each of its two ends: 2 × 12 = 24.

What is the time of BFS on a graph kept in adjacency lists?

Show the answer

The answer is B. Every vertex enters the queue once and every list is read once. With a matrix the same search takes O(V²).

When Kahn's algorithm ends, some vertices did not make it into the order. What does that tell you?

Show the answer

The answer is B. The in-degree of a vertex on a cycle never reaches 0. All the vertices of a DAG that is not connected still get in.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.