Chapter 15: Graphs
Introduction
Learning Outcomes
Use G = (V, E), directed/undirected graphs, adjacency, subgraphs, paths, degree and connectivity.
Justify that the degree sum = 2e (Theorem 1) and that connectivity needs e ≥ n − 1.
Build adjacency matrices, adjacency lists, sequential arrays, orthogonal lists and adjacency multilists in C.
Code and trace depth-first (DFS) and breadth-first (BFS) search; analyze them as O(n + e).
Find connected components, cycles and bipartiteness with DFS/BFS.
Pick the right representation from the operations the problem needs: “data structure first, then code”.
Introduction
The problem: the 7 Bridges of Königsberg
On the Pregel river, two islands (A, D) and two banks (B, C) are joined by 7 bridges. Can you cross every bridge exactly once and return to the start?
Euler (1736) made the land masses vertices and the bridges edges: what matters is not the shape but the connections (notation, not drawing).
Such a walk exists only if every vertex has even degree. Here all degrees are odd (5, 3, 3, 3) → no such walk.
Definitions and Terminology
Definition: G = (V, E)
A graph G consists of two finite sets: a nonempty set V of vertices (nodes) and a possibly empty set E of edges (arcs). Undirected: (v0, v1) ≡ (v1, v0); directed (digraph): <v0, v1> ≠ <v1, v0> — <tail, head>: the arrow leaves the tail and points into the head.
| Graph | V(G) | E(G) |
|---|---|---|
| G1 | {0, 1, 2, 3} | {(0,1), (0,2), (0,3), (1,2), (1,3), (2,3)} |
| G2 | {0, …, 6} | {(0,1), (0,2), (1,3), (1,4), (2,5), (2,6)} |
| G3 | {0, 1, 2} | {<0,1>, <1,0>, <1,2>} — both are listed in a digraph |
E is a subset of the Cartesian product V × V (it need not contain every pair).
Definitions and Terminology
Where Is the Graph Data Structure Used?
Analyzing electrical circuits, project planning (activity networks), identifying chemical compounds.
Shortest paths, routing, many problems on computer networks.
Trees are graphs; topological sorting, finite automata.
Flow in transport networks; max flow: moving as much oil/water as possible from source to sink.
Minimum spanning tree: connecting villages with the least cable.
Is the graph connected, how many components, is a network broken?
Definitions and Terminology
Terminology: Adjacent Vertices, Subgraphs
If (v0, v1) is an edge of an undirected graph, v0 and v1 are adjacent, and the edge is incident on both.
If G′ is a subgraph of G, then V(G′) ⊆ V(G) and E(G′) ⊆ E(G). A single vertex is also a subgraph.
Definitions and Terminology
Path, Connectivity and Degree
- Path: a sequence of vertices from vp to vq such that (vp, vi1), (vi1, vi2), …, (vin, vq) are edges.
- If there is a path from v0 to v1, they are connected; if every distinct pair (vi, vj) is joined by a path, G is connected.
- Degree: the number of edges incident on the vertex. In G2 d(0) = 2, in G1 d(1) = 3, in G2 d(4) = 1.
- In a digraph, degree = in-degree + out-degree. In G3 d(0) = 1 + 1 = 2; d(1) = 1 + 2 = 3; d(2) = 1 + 0 = 1.
Vertex 0 in G3: d = 1 + 1 = 2
Definitions and Terminology
Theorem 1: The Sum of Degrees = 2e
In a graph G with n vertices and e edges, 2e = d0 + d1 + … + dn−1. Proof: each edge adds exactly 2 to the degree sum of its two endpoints. It holds for simple and non-simple (multi-edge) graphs. Simple graph: at most one edge between two vertices, no self-loops.
Edge 1 added: each endpoint's degree rose by 1 → the sum rose by 2.
Edge 2 added: each endpoint's degree rose by 1 → the sum rose by 2.
Edge 3 added: each endpoint's degree rose by 1 → the sum rose by 2.
Edge 4 added: each endpoint's degree rose by 1 → the sum rose by 2.
Edge 5 added: each endpoint's degree rose by 1 → the sum rose by 2.
Edge 6 added: each endpoint's degree rose by 1 → the sum rose by 2.
Representations
How Do We Represent a Graph in Memory?
Representations
1. Adjacency Matrix
For G with n vertices, an n × n matrix: a[i][j] = 1 if (i, j) ∈ E. For an undirected graph the matrix is symmetric; to save space only the lower or upper triangle may be stored — memory is still O(n²).
| 0 | 1 | 2 | 3 | |
|---|---|---|---|---|
| 0 | 0 | 1 | 1 | 1 |
| 1 | 1 | 0 | 1 | 1 |
| 2 | 1 | 1 | 0 | 1 |
| 3 | 1 | 1 | 1 | 0 |
| 0 | 1 | 2 | |
|---|---|---|---|
| 0 | 0 | 1 | 0 |
| 1 | 1 | 0 | 1 |
| 2 | 0 | 0 | 0 |
Count the 1s in the row (or column): O(n). In a digraph the row gives out-degree, the column in-degree; together O(2n). In G3 out-degree d(2) = 0, in-degree d(2) = 1.
Count all the 1s and divide by 2: O(n²). By symmetry half the matrix is enough; still O(n²/2) = O(n²).
Representations
G4's Adjacency Matrix — Checking Symmetry
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | |
|---|---|---|---|---|---|---|---|---|
| 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 |
| 1 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 |
| 2 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 |
| 3 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 |
| 4 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
| 5 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 |
| 6 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 |
| 7 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 |
G4: two components
1 0 1 0 … and row 7 as … 0 0 1. The matrix of an undirected graph must be symmetric; these rows break symmetry. Correct: row 1 1 0 0 1 0 0 0 0 (neighbors 0, 3), row 7 0 0 0 0 0 0 1 0 (neighbor 6).The number of components can also be found from the matrix: each DFS scans neighbors in O(n), so O(n²) in total.
Adjacency matrix · Run the code step by step
Code Trace: degree(a, 3, 1)
degree(a, 3, 1): finding the degree of vertex 1 in G3.
The counters are set to zero.
Row 1, column 0: a[1][0] = 1 → out = 1.
Row 1, column 1: a[1][1] = 0 → out = 1.
Row 1, column 2: a[1][2] = 1 → out = 2.
Column 1, row 0: a[0][1] = 1 → in = 1.
Column 1, row 1: a[1][1] = 0 → in = 1.
Column 1, row 2: a[2][1] = 0 → in = 1.
return 2 + 1 = 3. Both loops run n times → O(2n) = O(n).
int degree(int a[][MAX_V], int n, int v) { int j, out = 0, in = 0; for (j = 0; j < n; j++) out += a[v][j]; /* row */ for (j = 0; j < n; j++) in += a[j][v]; /* column */ return out + in; }
Representations
2. Adjacency Lists
Instead of each matrix row, a linked list: graph[i] points to the list of i's neighbors. Drawback: an undirected graph uses 2 nodes per edge.
#define MAX_V 50 /* max number of vertices */ typedef struct node *node_ptr; typedef struct node { int vertex; /* the neighbor's number */ node_ptr link; /* next neighbor in list */ } node; /* don't forget ';' and the name */ node_ptr graph[MAX_V]; /* one list per vertex */
G1 represented with adjacency lists
Count all the nodes and divide by 2 (Theorem 1): O(n + e). In graph theory, complexity is usually stated in terms of e.
In an undirected graph, counting the nodes in list i is enough: O(di).
Representations
Adjacency Lists: Undirected and Directed Examples
If the lists are sorted, in each list we can count the nodes whose number is below the head's (e.g. (1,0)) and skip the rest; we visit half the vertices, but it is still O(n + e).
<0,1> ≠ <1,0> → every edge must be counted. Out-degree is easy from the lists; in-degree requires scanning every list. The fix: also keep the inverse (transpose) lists, built in a single pass.
Representations
A Sparse Graph: 11 Vertices, 2 Edges
Lists: graph[1] → 4, graph[4] → 1, graph[7] → 8, graph[8] → 7. The other 7 heads are NULL.
Total: 11 heads + 2e = 4 nodes. Matrix: 11 × 11 = 121 cells.
Adjacency lists · Run the code step by step
Code Trace: adding edges to the structure
Edge (0,1) → first add_edge(0, 1): memory for a new node is allocated (NULL check!).
p->vertex = 1, p->link = NULL, graph[0] = p: the node went to the front of the list.
Edge (0,1) → then add_edge(1, 0): memory for a new node is allocated (NULL check!).
p->vertex = 0, p->link = NULL, graph[1] = p: the node went to the front of the list.
Edge (0,2) → first add_edge(0, 2): memory for a new node is allocated (NULL check!).
p->vertex = 2, p->link = &node(1), graph[0] = p: the node went to the front of the list.
Edge (0,2) → then add_edge(2, 0): memory for a new node is allocated (NULL check!).
p->vertex = 0, p->link = NULL, graph[2] = p: the node went to the front of the list.
Edge (1,2) → first add_edge(1, 2): memory for a new node is allocated (NULL check!).
p->vertex = 2, p->link = &node(0), graph[1] = p: the node went to the front of the list.
Edge (1,2) → then add_edge(2, 1): memory for a new node is allocated (NULL check!).
p->vertex = 1, p->link = &node(0), graph[2] = p: the node went to the front of the list.
void add_edge(int u, int v) /* u -> v */ { node_ptr p = malloc(sizeof(node)); if (p == NULL) exit(1); /* no memory */ p->vertex = v; p->link = graph[u]; /* at front: O(1) */ graph[u] = p; }
Representations
Who Builds the Graph?
Each edge is placed in O(1); the list ends up in the reverse of arrival order. Total build time O(n + e).
Keeps the order, but each time you must walk to the NULL (O(d)); or keep a last pointer for each list.
Keeping each list sorted by vertex number: edge counting and traversal order become predictable; insertion is O(d).
At the end of the program, every graph[i] list must be walked and freed.
Inverse adjacency lists · Run the code step by step
Code Trace: transpose()
First the rev[] heads are set to NULL.
Edge <0,1>: 0 is added to list rev[1] (<1,0>).
Edge <1,0>: 1 is added to list rev[0] (<0,1>).
Edge <1,2>: 1 is added to list rev[2] (<2,1>).
adj[2] is empty: no edges leave 2.
Each node was looked at once: the transpose was built in O(n + e). Now in-degree is also found in O(d).
void transpose(node_ptr adj[], node_ptr rev[], int n) { int i; node_ptr p; for (i = 0; i < n; i++) rev[i] = NULL; for (i = 0; i < n; i++) for (p = adj[i]; p; p = p->link) insert(rev, p->vertex, i); /* <j,i> */ }
Representations
3. Sequential Representation with an Array
Undirected, n vertices, e edges: a single array int vertex[n + 2*e + 1]. The first n + 1 cells are starting indices; the neighbors of i are in vertex[vertex[i]] … vertex[vertex[i+1] − 1].
The array for G4. Each edge is still stored twice, but there are no pointers.
Ex. 1: from [0] = 9 (incl.) to [1] = 11 (excl.): indices 9 and 10 → neighbors 1, 2.
Ex. 2: [1] = 11, [2] = 13 → indices 11, 12 → neighbors 0, 3.
Ex. 3: [7] = 22, [8] = 23 → only index 22 → a single neighbor, 6.
Sequential representation · Run the code step by step
Code Trace: print_adj(vertex, 5)
print_adj(vertex, 5): the neighbors of vertex 5.
k = 18 < vertex[6] = 20 → vertex[18] = 4 is printed.
k = 19 < vertex[6] = 20 → vertex[19] = 6 is printed.
k = 20 = vertex[6] → the loop ends. Neighbor count = vertex[6] − vertex[5] = the degree: O(d).
void print_adj(const int vertex[], int i) { int k; for (k = vertex[i]; k < vertex[i + 1]; k++) printf("%d ", vertex[k]); printf("\n"); }
Representations
4. Orthogonal Representation of Digraphs
G3: each edge node sits in one row list (out) and one column list (in) at the same time
Column link, for the head: where we come into this vertex from. Row link, for the tail: where we go from this vertex. One node per edge is enough.
It resembles the linked sparse matrix structure; it can be made circular, doubly linked, with head nodes. “Using 2e nodes bothered us, so we found this one.”
Representations
5. Adjacency Multilists
typedef struct edge *edge_ptr; typedef struct edge { short marked; /* processed? */ int vertex1, vertex2; /* ends */ edge_ptr list1; /* next for vertex1 */ edge_ptr list2; /* next for vertex2 */ } edge; edge_ptr graph[MAX_V];
The edge is the basic unit: there is one node for (vi, vj), but it is on both vi's and vj's lists. marked stops a processed edge from being handled again. To carry data on a vertex, add a field such as char data.
| Node | vertex1 | vertex2 | list1 | list2 |
|---|---|---|---|---|
| N0 | 0 | 1 | N1 | N3 |
| N1 | 0 | 2 | N2 | N3 |
| N2 | 0 | 3 | NULL | N4 |
| N3 | 1 | 2 | N4 | N5 |
| N4 | 1 | 3 | NULL | N5 |
| N5 | 2 | 3 | NULL | NULL |
Heads for G1: graph[0] = N0, graph[1] = N0, graph[2] = N1, graph[3] = N2. A vertex with no edges has a NULL head.
Adjacency multilist · Run the code step by step
Code Trace: walking over the neighbors of 2
p = graph[2] = N1: the first edge of 2.
N1 = (0,2): v is vertex2 → print the other end, 0.
Follow the link: p = p->list2 = N3.
N3 = (1,2): v is vertex2 → print the other end, 1.
Follow the link: p = p->list2 = N5.
N5 = (2,3): v is vertex1 → print the other end, 3.
Follow the link: p = p->list1 = NULL.
NULL: no more matching nodes. The neighbors of 2 are 0, 1, 3 — each edge was stored only once.
void print_adj(int v) { edge_ptr p = graph[v]; while (p) { if (p->vertex1 == v) { /* v: vertex1 */ printf("%d ", p->vertex2); p = p->list1; } else { /* v: vertex2 */ printf("%d ", p->vertex1); p = p->list2; } } }
Representations
Adding an Edge to an Adjacency Multilist
- Traversal: follow list1 if v is vertex1, list2 if v is vertex2. Stop at NULL. “Any more? Follow the link!”
- Insertion: you could walk the list to NULL and append; but inserting at the front saves the walk: O(1).
- An undirected graph needs one head array; a digraph keeps a tail array as well.
- The gain: only e nodes instead of 2e.
void ml_add_edge(int u, int v) { edge_ptr p = malloc(sizeof(edge)); if (p == NULL) exit(1); p->marked = 0; p->vertex1 = u; p->vertex2 = v; p->list1 = graph[u]; /* u's list */ p->list2 = graph[v]; /* v's list */ graph[u] = graph[v] = p; /* front of both */ }
Representations
Exercise: <0,1>, <0,3>, <1,2>, <2,0>, <3,2>
For the digraph with this edge list, give the adjacency matrix, the adjacency lists (and their inverse) and the orthogonal lists.
| 0 | 1 | 2 | 3 | |
|---|---|---|---|---|
| 0 | 0 | 1 | 0 | 1 |
| 1 | 0 | 0 | 1 | 0 |
| 2 | 1 | 0 | 0 | 0 |
| 3 | 0 | 0 | 1 | 0 |
Matrix: a[i][j] = 1 if <i,j> exists. Row sums are out-degrees (2, 1, 1, 1), column sums in-degrees (1, 1, 2, 1).
outgoing (adjacency lists)
incoming (transpose of the lists)
Lists and inverse: 2e = 10 nodes in all.
| Node | tail | head | tail link | head link |
|---|---|---|---|---|
| N1 | 0 | 1 | N2 | NULL |
| N2 | 0 | 3 | NULL | NULL |
| N3 | 1 | 2 | NULL | N5 |
| N4 | 2 | 0 | NULL | NULL |
| N5 | 3 | 2 | NULL | NULL |
| Vertex | tail (out) | head (in) |
|---|---|---|
| 0 | N1 | N4 |
| 1 | N3 | N1 |
| 2 | N4 | N3 |
| 3 | N5 | N2 |
Orthogonal: only e = 5 nodes (N1…N5). Each node is on its tail's out-list and its head's in-list.
Representations
Takeaway: First Decide How the Data Is Stored
| Representation | Memory | (u,v) present? | u's neighbors | Insert/delete |
|---|---|---|---|---|
| Adjacency matrix | O(n²) | O(1) | O(n) | O(1) |
| Adjacency lists | O(n + 2e) | O(du) | O(du) | front O(1) / search O(d) |
| Sequential array | n + 2e + 1 | O(du) | O(du) | expensive (shifting) |
| Orthogonal (directed) | O(n + e) | O(d) | in and out O(d) | O(1) at front |
| Multilist | O(n + e) | O(du) | O(du) | O(1) at front |
Representations
Weighted Graph Representation
weight = distance, cost, time…
| A | B | C | D | |
|---|---|---|---|---|
| A | 0 | 4 | 2 | ∞ |
| B | 4 | 0 | 1 | 5 |
| C | 2 | 1 | 0 | 8 |
| D | ∞ | 5 | 8 | 0 |
#define INF 1000000 /* not INT_MAX: sums overflow */ int cost[MAX_V][MAX_V]; typedef struct wnode *wnode_ptr; typedef struct wnode { int vertex; int weight; /* cost of the edge */ wnode_ptr link; } wnode; wnode_ptr wgraph[MAX_V];
- In the matrix, a weight instead of 1, and ∞ when there is no edge.
- In the lists, a
weightfield is added to the node. - Using
INT_MAXfor ∞ overflows in the sumd + w; choose a safe large constant. - MST and shortest-path algorithms use this representation.
Traversals
Basic Graph Operations: Traversal
- Given an undirected G = (V, E) and a vertex v, visit every vertex reachable from v (visit = print its data field).
- Depth-first search (DFS) resembles preorder traversal of a tree.
- Breadth-first search (BFS) resembles level-order traversal of a tree.
- Both use a graph stored as adjacency lists; the lists are sorted.
Sample graph
graph[] adjacency lists
Traversals
Depth-First Search (DFS)
- Visit v; pick an unvisited w from v's list and continue the search from w.
- A stack is needed to remember our place in the list; when u has nowhere left to go, pop a vertex from the stack and continue.
- A recursive routine makes this seemingly complex scheme easy: the stack is the call stack.
- The global array
visited[]must start out FALSE.
#include <stdio.h> #include <stdbool.h> #define TRUE true #define FALSE false bool visited[MAX_V]; /* don't forget ';' */
void dfs(int v) /* depth-first search */ { node_ptr w; visited[v] = TRUE; /* visited */ printf("%d ", v); for (w = graph[v]; w; w = w->link) if (!visited[w->vertex]) dfs(w->vertex); }
Depth-first search · Run the code step by step
Code Trace: dfs(0)
dfs(0) is called: 0 is marked and printed.
0 → 1: 1 is unvisited → dfs(1). 1 is marked and printed.
w → 0: visited[0] is TRUE; skip.
1 → 3: 3 is unvisited → dfs(3). 3 is marked and printed.
w → 1: visited[1] is TRUE; skip.
3 → 7: 7 is unvisited → dfs(7). 7 is marked and printed.
w → 3: visited[3] is TRUE; skip.
7 → 4: 4 is unvisited → dfs(4). 4 is marked and printed.
w → 1: visited[1] is TRUE; skip.
w → 7: visited[7] is TRUE; skip.
(dfs(4) is done.) 7 → 5: 5 is unvisited → dfs(5). 5 is marked and printed.
5 → 2: 2 is unvisited → dfs(2). 2 is marked and printed.
w → 0: visited[0] is TRUE; skip.
w → 5: visited[5] is TRUE; skip.
void dfs(int v) /* depth-first search */ { node_ptr w; visited[v] = TRUE; /* visited */ printf("%d ", v); for (w = graph[v]; w; w = w->link) if (!visited[w->vertex]) dfs(w->vertex); }
Depth-first search · Run the code step by step
Code Trace: dfs(0) (cont.)
2 → 6: 6 is unvisited → dfs(6). 6 is marked and printed.
w → 2: visited[2] is TRUE; skip.
w → 7: visited[7] is TRUE; skip.
dfs(6), dfs(2) are done; resume where 5 left off. w → 7: visited[7] is TRUE; skip.
dfs(5) is done; resume where 7 left off. w → 6: visited[6] is TRUE; skip.
dfs(7), dfs(3) are done; resume where 1 left off. w → 4: visited[4] is TRUE; skip.
dfs(1) is done; resume where 0 left off. w → 2: visited[2] is TRUE; skip.
dfs(0) is done. Visit order 0 1 3 7 4 5 2 6; the orange edges form a tree.
void dfs(int v) /* depth-first search */ { node_ptr w; visited[v] = TRUE; /* visited */ printf("%d ", v); for (w = graph[v]; w; w = w->link) if (!visited[w->vertex]) dfs(w->vertex); }
Traversals
What Does the DFS Result Depend On?
From 0: 0 1 3 7 4 5 2 6. The start need not be 0: from 6, 6 2 0 1 3 7 4 5; from 4, 4 1 0 2 5 7 3 6. Same vertices, different order.
Had 0's list been {2, 1} instead of {1, 2}, the order would be 0 2 5 7 3 1 4 6. Whether lists were built by inserting at the front or end, or kept sorted, changes the traversal.
dfs is called at most once per vertex; each list is scanned once: O(n + e). There are at most n(n − 1)/2 edges.
With a matrix, finding v's neighbors would take O(n), O(n²) in total. With lists we traverse in linear time.
Traversals
Breadth-First Search (BFS)
- Start at v and mark it; then visit all the vertices on v's list.
- Then the unvisited neighbors of the first vertex on v's list, then those of the second…
- A visited vertex goes into a queue (first in, first out); when a list is finished, a vertex is taken from the queue and its list is scanned.
- The search ends when the queue is empty.
void bfs(int v) /* breadth-first search */ { node_ptr w; queue_ptr front = NULL, rear = NULL; 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; } } }
Traversals
The Dynamic Queue Used by BFS
typedef struct queue *queue_ptr; typedef struct queue { int vertex; queue_ptr link; } queue; void addq(queue_ptr *f, queue_ptr *r, int d) { queue_ptr p = malloc(sizeof(queue)); if (p == NULL) exit(1); p->vertex = d; p->link = NULL; if (*f) (*r)->link = p; else *f = p; *r = p; }
int deleteq(queue_ptr *f, queue_ptr *r) { queue_ptr p = *f; /* f != NULL */ int d = p->vertex; *f = p->link; if (*f == NULL) *r = NULL; free(p); return d; }
int deleteq(queue_ptr *), taking only the front pointer, is not enough. When the queue empties, the rear pointer must become NULL too, so deleteq also gets r.Breadth-first search · Run the code step by step
Code Trace: bfs(0)
0 is printed, marked and added to the queue.
The queue is not empty: the front item 0 is removed; now 0's list is scanned.
w → 1: unvisited → printed, added to the rear of the queue, marked.
w → 2: unvisited → printed, added to the rear of the queue, marked.
The queue is not empty: the front item 1 is removed; now 1's list is scanned.
w → 3: unvisited → printed, added to the rear of the queue, marked. (0 was already marked.)
w → 4: unvisited → printed, added to the rear of the queue, marked.
The queue is not empty: the front item 2 is removed; now 2's list is scanned.
w → 5: unvisited → printed, added to the rear of the queue, marked. (0 was already marked.)
w → 6: unvisited → printed, added to the rear of the queue, marked.
The queue is not empty: the front item 3 is removed; now 3's list is scanned.
w → 7: unvisited → printed, added to the rear of the queue, marked. (1 was already marked.)
front = rear = NULL; 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; } }
Breadth-first search · Run the code step by step
Code Trace: bfs(0) (cont.)
The queue is not empty: the front item 4 is removed; now 4's list is scanned.
The queue is not empty: the front item 5 is removed; now 5's list is scanned.
The queue is not empty: the front item 6 is removed; now 6's list is scanned.
The queue is not empty: the front item 7 is removed; now 7's list is scanned.
The queue is empty → the search ends. Order 0 1 2 3 4 5 6 7: level by level. The orange edges are the breadth-first spanning tree.
front = rear = NULL; 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; } }
Traversals
BFS: Analysis and Beyond
Each vertex enters the queue once → the while loop runs n times. The lists hold 2e nodes in all: d0 + … + dn−1 = 2e. Total O(n + e); with a matrix O(n²).
Visits in order of number of edges (level) from the start; the shortest-path tree of an unweighted graph.
The ideas of depth-first/breadth-first search reappear in AI when a search space is traversed as a tree: minimax, B* search, branch and bound.
DFS: stack/recursion, goes deep (components, cycles, topological thinking). BFS: queue, layer by layer (path with fewest edges).
Components and Beyond
Connected Components
void connected(int n) { int i; for (i = 0; i < n; i++) if (!visited[i]) { /* new */ dfs(i); printf("\n"); } }
Is the undirected graph connected, and how many components does it have? Each DFS (or BFS) call marks one whole component; increment a counter on each new line and you get the number of components too.
Output: 0 1 3 2 / 4 5 6 / 7 8 9
Output: 0 / 1 2 4 3 / 5 6 7 8 / 9 10
Connected components · Run the code step by step
Code Trace: connected(10)
i = 0: unmarked → a new component; dfs(0) visits 0 1 3 2.
dfs returned; go to a new line.
i = 1: already marked (visited by the previous DFS) → the if is skipped, O(1).
i = 2: already marked (visited by the previous DFS) → the if is skipped, O(1).
i = 3: already marked (visited by the previous DFS) → the if is skipped, O(1).
i = 4: unmarked → a new component; dfs(4) visits 4 5 6.
dfs returned; go to a new line.
i = 5: already marked (visited by the previous DFS) → the if is skipped, O(1).
i = 6: already marked (visited by the previous DFS) → the if is skipped, O(1).
i = 7: unmarked → a new component; dfs(7) visits 7 8 9.
dfs returned; go to a new line.
i = 8: already marked (visited by the previous DFS) → the if is skipped, O(1).
i = 9: already marked (visited by the previous DFS) → the if is skipped, O(1).
The loop is done: 3 components. Every vertex and every list was processed once in total.
void connected(int n) { int i; for (i = 0; i < n; i++) if (!visited[i]) { /* new */ dfs(i); printf("\n"); } }
Components and Beyond
Analysis: n × O(n + e)?
The outer for runs n times, and the inner dfs() was O(n + e). Is the complexity their product, O(n²)?
With a single component, the first iteration runs in O(n + e) and every visited[] becomes TRUE; for the other values of i the if is skipped. The components are disjoint, so the total work is O(n + e).
Each dfs call searches for neighbors in O(n) → finding components is O(n²). “If that is written efficiently too…”
Components and Beyond
Theorem: A Connected Graph Has at Least n − 1 Edges
- Theorem: a graph needs at least n − 1 edges to be connected.
- It is one-way: n − 1 edges are necessary but not sufficient; a graph with n − 1 edges may or may not be connected. With fewer it is certainly not connected.
- At most: if all vertices are adjacent to each other (the complete graph Kn), (n − 1) + (n − 2) + … + 1 = n(n − 1)/2. So e can be quadratic in n.
- In a connected graph: n − 1 ≤ e ≤ n(n − 1)/2.
Cycles with DFS · Run the code step by step
Code Trace: does an undirected graph have a cycle?
has_cycle(0, -1): 0 is marked.
has_cycle(1, 0): 1 is marked.
w → 0: marked, but it is 1's parent; the edge we came in on is not a cycle.
has_cycle(2, 1): 2 is marked.
w → 1: marked, but it is 2's parent; the edge we came in on is not a cycle.
has_cycle(3, 2): 3 is marked.
w → 1: marked and not the parent (2) → a back edge (3,1): there is a cycle! TRUE is passed up.
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; }
Components and Beyond
Cycle Detection: Undirected and Directed
In DFS, a visited neighbor that is not the parent = a back edge = a cycle. O(n + e).
An edge to a vertex “currently on the stack” (gray) is a cycle; three colors: white/gray/black. A topological sort routine also catches cycles.
With prerequisite tasks, a cycle means the project never finishes; in an MST, a cycle means an extra edge.
The same DFS becomes O(n²) with a matrix.
Components and Beyond
Bipartite Graph Test
- V can be split into two sets with every edge joining different sets: a bipartite graph (e.g. K3,3, students–courses).
- Test: two-color with BFS, giving each neighbor the opposite color. If an edge joins two same-colored vertices, it is not bipartite.
- Theorem: a graph is bipartite ⇔ it has no odd-length cycle.
- Same cost as BFS: O(n + e); start it separately for each component.
BFS: 0 colored (color 0). Each neighbor gets the opposite color.
BFS: 1 colored (color 1). Each neighbor gets the opposite color.
BFS: 5 colored (color 1). Each neighbor gets the opposite color.
BFS: 2 colored (color 0). Each neighbor gets the opposite color.
BFS: 4 colored (color 0). Each neighbor gets the opposite color.
BFS: 3 colored (color 1). Each neighbor gets the opposite color.
Triangle: 0 colored.
Triangle: 1 colored.
Triangle: 2 colored.
Two adjacent vertices with the same color → not bipartite (there is an odd cycle).
Lab · C code step by step
Lab: DFS and BFS
Summary
Complexity Summary
| Operation | Matrix | Lists | Note |
|---|---|---|---|
| Memory | O(n²) | O(n + e) | 2e nodes in undirected lists |
| Degree (undirected) | O(n) | O(d) | inverse lists for in-degree in digraphs |
| Number of edges | O(n²) | O(n + e) | Theorem 1: sum / 2 |
| DFS / BFS | O(n²) | O(n + e) | each vertex once |
| Connected components | O(n²) | O(n + e) | not a product! |
| Cycles / bipartiteness | O(n²) | O(n + e) | on top of DFS / BFS |
| Building transpose lists | — | O(n + e) | in a single pass |
n: number of vertices · e: number of edges · d: degree of a vertex · n − 1 ≤ e ≤ n(n − 1)/2 (connected simple graph)
Summary
Common Mistakes
visited[] to FALSE before each traversal (a global array!).malloc when building lists; not freeing the lists at the end of the program.Summary
Exercises
- Is there a simple undirected graph with degree sequence (3, 3, 2, 2, 1)? How many edges does it have?
- In the sequential array representation of G4, which indices hold the neighbors of vertex 5?
- Run DFS and BFS on the 8-vertex sample graph starting at 7 (lists sorted).
- What happens if the line
visited[w->vertex] = TRUEin the BFS code is moved afterdeleteq? - Write a routine that counts the components of a graph given as an adjacency matrix; what is its complexity?
- To report in-degree in O(1) for a digraph, which structure would you keep, and how would you update it?
Answers / hints
- The sum is 11, which is odd → it cannot be 2e (Theorem 1). No such graph exists.
- vertex[5] = 18, vertex[6] = 20 → indices 18, 19: neighbors 4 and 6.
- DFS(7): 7 3 1 0 2 5 6 4 · BFS(7): 7 3 4 5 6 1 2 0.
- The same vertex can enter the queue more than once (e.g. 7, through both 3 and 4); output repeats and the work exceeds O(e).
- For each unmarked i, a DFS that scans matrix rows: O(n²).
- An
in[]counter per vertex (or inverse lists), updated whenever an edge is added or removed.
Summary
Chapter Summary
G = (V, E); directed/undirected, adjacent, subgraph, path, degree; Σd = 2e; connectivity needs e ≥ n − 1.
Matrix O(n²); lists O(n + e); sequential array; orthogonal (directed); multilist (one node per edge).
DFS = recursion/stack; BFS = queue. Both O(n + e) with lists, O(n²) with a matrix.
Connected components in O(n + e); cycle detection; bipartite test; groundwork for spanning trees.
First the problem, then how the data is stored; don't trust the first solution.
Summary
References
- E. Horowitz, S. Sahni, S. Anderson-Freed, Fundamentals of Data Structures in C, 2nd ed., Chapter 6 (Graphs).
- T. H. Cormen et al., Introduction to Algorithms, 4th ed., Chapter 20 (Elementary Graph Algorithms).
- R. Sedgewick, Algorithms in C, Part 5: Graph Algorithms, 3rd ed.