Chapter 15: Graphs

Data Structures and Algorithms with C · Study Questions
KönigsbergDegree and edgesMatrix and listSequential and multilist representationsDFSBFSComponents and cycles
Sercan KÜLCÜ · Giresun University · Computer Engineering

Multiple Choice · Introduction

Question 1: Adding a Bridge to Königsberg

In the Königsberg graph the degrees are A: 5, B: 3, C: 3, D: 3. What is the minimum number of new bridges needed for a walk that crosses every bridge exactly once and returns to its start?

B: Such a walk needs every degree to be even. A new bridge raises the degrees of its two ends by one each; if the four odd-degree vertices are paired up (e.g. A–B and C–D), 2 bridges suffice. A single bridge fixes only two vertices; two odd-degree vertices remain.

Multiple Choice · Definitions and Terminology

Question 2: Number of Edges from the Degrees

How many edges does a simple undirected graph have if its vertex degrees are 4, 3, 3, 2, 2, 2?

D: By Theorem 1 the degree sum is 2e: 4 + 3 + 3 + 2 + 2 + 2 = 16 → e = 8. Each edge adds one to the degree of each of its two ends; 16 counts edge ends, not edges. Such a graph really exists; e.g. adding two chords from the same vertex (0–2 and 0–4) to a 6-vertex cycle gives these degrees.

Classic Question · Representations

Question 3: Matrix of a Directed Graph

A directed graph has the edges <0,1>, <0,2>, <1,2>, <2,0>, <2,3>, <3,1>. Write its adjacency matrix and find the in-degree and out-degree of every vertex. What does the slides' degree(a, 4, 2) return? Is the matrix symmetric?

0123
Show answer
tail \ head0123out
001102
100101
210012
301001
in1221

A row sum is the out-degree, a column sum is the in-degree. degree(a, 4, 2) = 2 + 2 = 4; two loops run n times each: O(n).

It is not symmetric: a[0][1] = 1 but a[1][0] = 0. Only the pair <0,2> and <2,0> looks symmetric. Sum of out-degrees = sum of in-degrees = e = 6.

Output Question · Representations

Question 4: Front Insertion and the DFS Order

The edges (0,1), (0,2), (1,3), (2,3) are added to empty lists in this order, each with add_edge(u, v); add_edge(v, u);. What do the lists look like, and what does the slides' dfs(0) print? How many free calls are needed at the end?

void add_edge(int u, int v) {  /* u -> v */
  node_ptr p = malloc(sizeof(node));
  if (p == NULL) exit(1);
  p->vertex = v;
  p->link = graph[u];   /* at the front */
  graph[u] = p;
}
Show answer
  • New nodes enter at the front, so each list is in reverse arrival order:
graph[0]2 → 1
graph[1]3 → 0
graph[2]3 → 0
graph[3]2 → 1

dfs(0): in 0's list first 2 → in 2's list 3 → in 3's list 2 (marked), 1 → 0 2 3 1. With sorted lists it would print 0 1 3 2.

2 nodes per edge: 8 malloc; at the end 8 free, walking the lists.

Multiple Choice · Representations

Question 5: Sequential Array Representation

An undirected graph is stored in the sequential representation shown below. What does print_adj(vertex, 3) print?

int vertex[] = {6, 8, 11, 13, 15, 16,
               1, 2, 0, 2, 3, 0, 1, 1, 4, 3};
void print_adj(const int vertex[], int i) {
  for (int k = vertex[i]; k < vertex[i + 1]; k++)
    printf("%d ", vertex[k]);
}

C: n = 5, e = 5 → the array has n + 2e + 1 = 16 cells. The neighbors of 3 are vertex[vertex[3]] … vertex[vertex[4] − 1], that is indices 13 and 14: 1 and 4. The degree is read in O(1) as vertex[4] − vertex[3] = 2.

Multiple Choice · Representations

Question 6: Adjacency List versus Multilist

An adjacency list and a multilist are compared for an undirected graph with e edges (header arrays excluded). Which statement is correct?

A: In an adjacency list each edge is one node in the lists of both ends (one link per node). In a multilist the edge is one node that enters two lists: list1 and list2. The link count is the same; the gain is that vertex numbers and edge data (weight, mark) are not stored twice.

Spot the Bug · Representations

Question 7: INT_MAX as Infinity

A weighted graph uses INT_MAX for “no edge / not reached yet”. What does the code do? What is the bug and how is it fixed?

#include <limits.h>
#define INF INT_MAX
int d[3] = {0, INF, INF};
int w = 5;           /* edge (1,2) */
if (d[1] + w < d[2]) /* shorter? */
  d[2] = d[1] + w;
printf("%d\n", d[2]);
Show answer
  • d[1] + w = INT_MAX + 5: a signed integer overflow, which is undefined behavior in C. Compiled with -fsanitize=undefined, the program stops with a “signed integer overflow” message.
  • In a build where the overflow wraps around, the sum is −2147483644; being smaller than INT_MAX it is stored in d[2] and the screen shows −2147483644: the unreachable vertex looks the nearest.

Fix: choose a large constant whose sums cannot overflow, as the slides do (#define INF 1000000), or test before adding:

if (d[1] != INF && d[1] + w < d[2])
  d[2] = d[1] + w;

Classic Question · Representations

Question 8: Matrix or List?

A road network with 10,000 vertices and 20,000 undirected edges is stored. On a 64-bit system int is 4 bytes, a pointer 8, and sizeof(node) 16. About how much memory do an int adjacency matrix and adjacency lists need? How long does DFS take on each?

Show answer
  • Matrix: 10,000 × 10,000 = 108 cells × 4 bytes = 400 MB (100 MB with char, 12.5 MB with bits). 99.96% of the cells are 0.
  • Lists: 10,000 headers × 8 = 80 KB; 2e = 40,000 nodes × 16 = 640 KB → about 720 KB.
  • DFS: with the matrix each vertex's row is scanned: n² = 108 steps; with lists n + 2e = 50,000 steps.

For a sparse graph (e ≪ n²) lists win in both memory and traversal. The matrix is chosen when “is there an edge (u, v)?” must be answered in O(1) and the graph is dense.

Step-by-Step Trace · Traversals

Question 9: dfs(0) Step by Step

The graph in the figure is stored with sorted adjacency lists. In what order does dfs(0) print the vertices? How does the call stack change? (Bold edges form the DFS tree.)

0142356

Lists (sorted): 0: 1 4 · 1: 0 2 3 · 2: 1 5 · 3: 1 5 · 4: 0 6 · 5: 2 3 6 · 6: 4 5.

0142356

0 is marked and printed. The first node in its list is 1.

0142356

1 is unvisited → dfs(1).

0142356

In 1's list 0 is marked, skipped; 2 → dfs(2).

0142356

2's list: 1 is marked, 5 → dfs(5).

0142356

5's list: 2 is marked, 3 → dfs(3). 3's neighbors 1 and 5 are marked: it returns at once.

0142356

Back in 5: the next neighbor is 6 → dfs(6).

0142356

6's list: 4 → dfs(4). The stack is at its deepest: 6 frames.

0142356

4's neighbors are marked; the frames close one by one, skipping 3 in 1 and 4 in 0. Order 0 1 2 5 3 6 4; 6 tree edges = n − 1. O(n + e).

void dfs(int v) {
  node_ptr w;
  visited[v] = TRUE;
  printf("%d ", v);
  for (w = graph[v]; w; w = w->link)
    if (!visited[w->vertex])
      dfs(w->vertex);
}

Step-by-Step Trace · Traversals

Question 10: bfs(0) Step by Step

The graph in the figure is stored with sorted adjacency lists and bfs(0) runs. In each round which vertex is taken from the queue, which are added, and what is the output? (Green: in the queue.)

0142356

0 is printed, marked and enters the queue.

0142356

0 is taken out; its neighbors 1 and 4 are printed, queued and marked.

0142356

1 is taken out: 0 is marked; 2 and 3 are added.

0142356

4 is taken out: 0 is marked; 6 is added.

0142356

2 is taken out: 1 is marked; 5 is added. All vertices are marked.

0142356

3 is taken out: 1 and 5 are marked, nothing to add.

0142356

6 is taken out: 4 and 5 are marked.

0142356

5 is taken out, nothing to add; the queue is empty. Levels: 0 | 1 4 | 2 3 6 | 5. The bold edges (BFS tree) give the fewest-edge paths.

printf("%d ", v);  visited[v] = TRUE;
addq(&front, &rear, v);
while (front) {
  v = deleteq(&front, &rear);
  for (w = graph[v]; w; w = w->link)
    if (!visited[w->vertex]) {
      printf("%d ", w->vertex);
      addq(&front, &rear, w->vertex);
      visited[w->vertex] = TRUE;
    }
}

Multiple Choice · Traversals

Question 11: Items Scanned by BFS

A connected undirected graph with 1000 vertices and 3000 edges is stored with adjacency lists. How many list nodes are scanned in total during bfs(0)?

D: Every vertex is taken from the queue once and its list is scanned once; the number of list nodes is the sum of the degrees, that is 2e = 6000. The total work is O(n + e). 1,000,000 (n²) is the cost of a traversal with a matrix.

Multiple Choice · Traversals

Question 12: If rear Is Not Set to NULL

What happens if the line if (*front == NULL) *rear = NULL; is deleted from deleteq in the BFS queue?

B: When the queue empties, rear points to the node just freed (a dangling pointer). But addq looks at *front first; if front is NULL it never touches (*rear)->link and links *front and *rear to the new node. On the example graph the output is the same. Still, the line must not be deleted: any other routine that reads rear falls into undefined behavior.

Output Question · Components and Beyond

Question 13: Output of connected

An undirected graph with 9 vertices has the edges (0,3), (1,4), (3,6), (2,5), (4,7), (6,8); the lists are sorted and visited[] starts as FALSE. What does connected(9) print? How many times is the if entered? Why is the total work not O(n · (n + e))?

void connected(int n) {
  int i;
  for (i = 0; i < n; i++)
    if (!visited[i]) {
      dfs(i);
      printf("\n");
    }
}
Show answer
0 3 6 8
1 4 7
2 5
  • i = 0: dfs(0) → 0, 3, 6, 8 are marked. i = 1: dfs(1) → 1, 4, 7. i = 2: dfs(2) → 2, 5. For the remaining i the vertex is marked: the if is entered 3 times → 3 components.
  • Each DFS walks only its own component; since components are disjoint, every vertex and every list is processed once in total. The n rounds of the outer loop add only O(n): O(n + e).

Coding Question · Components and Beyond

Question 14: Labeling Components

Write the routine int label_components(int n) that gives every vertex its component number: let label[v] be the number (0, 1, 2 …) of v's component, and let the routine return the number of components. Then “is there a path between u and v?” can be answered in O(1). Do not use the global visited[].

Show answer
int label[MAX_V];          /* -1: not labeled yet */
void label_component(int v, int id) {
  label[v] = id;
  for (node_ptr w = graph[v]; w; w = w->link)
    if (label[w->vertex] < 0)
      label_component(w->vertex, id);
}
int label_components(int n) {
  int i, count = 0;
  for (i = 0; i < n; i++) label[i] = -1;
  for (i = 0; i < n; i++)
    if (label[i] < 0) label_component(i, count++);
  return count;
}

label[] is both the mark array and the result; because it is reset to −1 on every call, the routine can be called again and again. Query: label[u] == label[v]. For example, on the 9-vertex graph with edges (0,3), (1,4), (3,6), (2,5), (4,7), (6,8) it returns 3 and the labels are 0 1 2 0 1 2 0 1 0. O(n + e).

Multiple Choice · Components and Beyond

Question 15: Edge Count and Connectivity

Which is true for a simple undirected graph with 10 vertices?

A: A connected graph needs e ≥ n − 1 = 9; but 9 edges can also be arranged, for example, as a 9-vertex cycle (9 edges) plus one isolated vertex. With 8 edges at least 2 components remain. A simple undirected graph has at most n(n − 1)/2 = 45 edges; 90 is the limit for a directed graph.

Step-by-Step Trace · Components and Beyond

Question 16: Cycle Detection Step by Step

In the graph in the figure the lists are sorted (0: 1 2 · 1: 0 3 · 2: 0 4 · 3: 1 5 · 4: 2 5 · 5: 3 4). Which calls does has_cycle(0, -1) make and on which edge does it catch the cycle?

012345

0 is marked; the first neighbor is 1.

012345

1 is unmarked → has_cycle(1, 0).

012345

In 1's list 0 is marked but is 1's parent → not counted as a cycle. 3 → has_cycle(3, 1).

012345

In 3, 1 is the parent, skipped; 5 → has_cycle(5, 3).

012345

In 5, 3 is the parent; 4 → has_cycle(4, 5).

012345

4's list: 2 is unmarked → has_cycle(2, 4). There are 6 frames on the stack.

012345

2's first neighbor is 0: marked and not the parent (4) → back edge (2, 0): the cycle is 0–1–3–5–4–2–0.

012345

TRUE is carried upward by return TRUE in every frame; the remaining neighbors are not examined. At most O(n + e).

bool has_cycle(int v, int parent) {
  node_ptr w;
  visited[v] = TRUE;
  for (w = graph[v]; w; w = w->link)
    if (!visited[w->vertex]) {
      if (has_cycle(w->vertex, v))
        return TRUE;
    } else if (w->vertex != parent)
      return TRUE;        /* back edge */
  return FALSE;
}

Multiple Choice · Components and Beyond

Question 17: Bipartite Graph

Which of the following graphs is bipartite (its vertices can be split into two sets so that every edge joins different sets)?

C: A graph is bipartite ⇔ it has no odd-length cycle. In the six-vertex cycle the vertices are colored alternately with two colors (0, 1, 0, 1, 0, 1) and no edge has both ends of the same color. The triangle and the five-cycle have odd length; attaching a leaf to a triangle does not remove the triangle.

The End

Chapter 15: Graphs: Study Questions
Lecture slides: Chapter 15: Graphs · Lecture notes
1 / 1 Sercan KÜLCÜ. All rights reserved.