The undirected graph has edges 1–2, 1–3, 2–4, 2–5, 3–6, 3–7, 5–7. Starting from vertex 1 and taking neighbours in increasing order, give the BFS order (with distances) and the DFS order.
A graph G = (V, E) models pairwise relationships — roads, networks, prerequisites. This topic covers graph vocabulary, adjacency-matrix and adjacency-list storage, BFS and DFS in O(V + E), and their uses: topological sort, components, cycle detection and bipartite testing.
A graph G = (V, E) is a set V of vertices (nodes) together with a set E of edges, each joining a pair of vertices. In an undirected graph an edge {u, v} can be travelled both ways; in a directed graph (digraph) an edge (u, v), also called an arc, goes only from its tail u to its head v. In a weighted graph every edge carries a number — a distance, cost or capacity. Trees and linked lists are special graphs, so graph algorithms generalise much of what you already know.
| Term | Meaning |
|---|---|
| Adjacent, incident | u and v are adjacent if an edge joins them; that edge is incident on both |
| Degree; in-degree, out-degree | edges touching a vertex; in a digraph, arcs entering / leaving it |
| Path, simple path, cycle | a sequence of edges; one that repeats no vertex; a path that returns to its start |
| Connected graph, component | every pair joined by a path; a maximal connected piece |
| Strongly connected (digraph) | a directed path exists from every vertex to every other |
| Complete graph Kₙ | every pair of distinct vertices is adjacent: n(n − 1)/2 edges (n(n − 1) arcs if directed) |
| Simple graph vs multigraph | no self-loops or parallel edges vs. allowed |
| Sparse vs dense | E close to V vs. E close to V² |
| DAG | directed acyclic graph — a digraph with no directed cycle |
| Tree, forest | connected acyclic graph (exactly n − 1 edges); a set of disjoint trees |
| Source, sink | vertex with in-degree 0; vertex with out-degree 0 |
| Isolated, pendant vertex | degree 0; degree 1 |
| Bipartite graph | vertices split into two sets with every edge going between the sets |
| Regular graph | every vertex has the same degree |
The running example for this topic is the undirected graph with vertices A–F and edges A–B, A–C, B–D, B–E, C–E, D–F and E–F (6 vertices, 7 edges).
An adjacency matrix is a V × V array with A[i][j] = 1 (or the edge weight) when there is an edge from i to j, and 0 (or ∞) otherwise. For an undirected graph it is symmetric; diagonal entries represent self-loops. It needs Θ(V²) space whatever the number of edges, answers ‘is there an edge u–v?’ in O(1), but needs O(V) to list a vertex's neighbours.
| A | B | C | D | E | F | deg | |
|---|---|---|---|---|---|---|---|
| A | 0 | 1 | 1 | 0 | 0 | 0 | 2 |
| B | 1 | 0 | 0 | 1 | 1 | 0 | 3 |
| C | 1 | 0 | 0 | 0 | 1 | 0 | 2 |
| D | 0 | 1 | 0 | 0 | 0 | 1 | 2 |
| E | 0 | 1 | 1 | 0 | 0 | 1 | 3 |
| F | 0 | 0 | 0 | 1 | 1 | 0 | 2 |
An adjacency list keeps, for each vertex, a list of its neighbours: A → B, C; B → A, D, E; C → A, E; D → B, F; E → B, C, F; F → D, E. An undirected graph stores every edge twice, so the lists hold 2E = 14 entries (a digraph's hold E). Space is Θ(V + E); listing a vertex's neighbours costs only its degree, but testing for a particular edge u–v means scanning u's list — O(deg(u)), which is O(V) in the worst case.
| Operation | Adjacency matrix | Adjacency list |
|---|---|---|
| Space | Θ(V²) | Θ(V + E) |
| Is (u, v) an edge? | O(1) | O(deg u) — worst O(V) |
| List all neighbours of u | O(V) | O(deg u) |
| Add an edge | O(1) | O(1) (insert at the head) |
| Complete BFS or DFS | O(V²) | O(V + E) |
| Best for | dense graphs, Floyd–Warshall, quick edge tests | sparse graphs (most real networks) |
Two other forms appear in textbooks: the incidence matrix (V × E, with a 1 where a vertex touches an edge) and the plain edge list of (u, v, weight) triples, which is what Kruskal's algorithm sorts.
#include <stdio.h>
#define V 6
#define MAXDEG 6
int adj[V][MAXDEG], deg[V]; /* neighbour lists */
const char *name = "ABCDEF";
void addEdge(int u, int v) { adj[u][deg[u]++] = v; adj[v][deg[v]++] = u; } /* undirected */
void bfs(int s) {
int visited[V] = {0}, queue[V], front = 0, rear = 0;
visited[s] = 1; queue[rear++] = s; /* mark when ENQUEUED */
while (front < rear) {
int u = queue[front++];
printf("%c ", name[u]);
for (int i = 0; i < deg[u]; i++) {
int v = adj[u][i];
if (!visited[v]) { visited[v] = 1; queue[rear++] = v; }
}
}
printf("\n");
}
int seen[V];
void dfs(int u) { /* recursion = implicit stack */
seen[u] = 1;
printf("%c ", name[u]);
for (int i = 0; i < deg[u]; i++)
if (!seen[adj[u][i]]) dfs(adj[u][i]);
}
int main(void) {
addEdge(0, 1); addEdge(0, 2); addEdge(1, 3); addEdge(1, 4); /* A-B A-C B-D B-E */
addEdge(2, 4); addEdge(3, 5); addEdge(4, 5); /* C-E D-F E-F */
printf("BFS: "); bfs(0); /* A B C D E F */
printf("DFS: "); dfs(0); printf("\n"); /* A B D F E C */
return 0;
}| Step | Dequeue | Newly discovered (dist) | Queue afterwards |
|---|---|---|---|
| 0 | — | A (0) | A |
| 1 | A | B (1), C (1) | B C |
| 2 | B | D (2), E (2) — A already seen | C D E |
| 3 | C | none — A and E already seen | D E |
| 4 | D | F (3) | E F |
| 5 | E | none | F |
| 6 | F | none | empty |
BFS order: A B C D E F. The parent links form the BFS tree A–B, A–C, B–D, B–E, D–F, and dist[] gives the fewest-edge distance from A to every vertex — BFS is the shortest-path algorithm for unweighted graphs. Every vertex is enqueued once and every adjacency list is scanned once, so BFS runs in O(V + E) with adjacency lists (O(V²) with a matrix) and needs O(V) extra space.
| Call | Neighbours examined | Action |
|---|---|---|
| DFS(A) | B | B unvisited → DFS(B) |
| DFS(B) | A (seen), D | D unvisited → DFS(D) |
| DFS(D) | B (seen), F | F unvisited → DFS(F) |
| DFS(F) | D (seen), E | E unvisited → DFS(E) |
| DFS(E) | B (seen), C | C unvisited → DFS(C) |
| DFS(C) | A (seen), E (seen) | C finishes; backtrack all the way to A |
DFS order: A B D F E C; finishing order C E F D B A. The DFS tree edges are A–B, B–D, D–F, F–E and E–C; the two remaining edges, A–C and B–E, are back edges joining a vertex to an ancestor — each one closes a cycle. In a digraph DFS also produces forward edges (to a descendant) and cross edges (between branches). DFS costs O(V + E) with lists, O(V²) with a matrix, and its recursion depth can reach V.
| Problem | Method | Key idea |
|---|---|---|
| Shortest path in an unweighted graph | BFS | the first time a vertex is discovered, it is by a fewest-edge path |
| Connected components | BFS or DFS | every restart from a still-unvisited vertex begins a new component |
| Cycle in an undirected graph | BFS or DFS | reaching an already-visited vertex that is not your parent |
| Cycle in a directed graph | DFS | an edge to a vertex still on the recursion stack (a back edge); or Kahn's algorithm outputs fewer than V vertices |
| Bipartite test | BFS 2-colouring | an edge between two vertices of the same colour means an odd cycle |
| Topological order of a DAG | DFS or Kahn | reverse finishing order, or repeatedly remove in-degree-0 vertices |
| Strongly connected components | two DFS passes (Kosaraju) or Tarjan's single pass | finishing times on G, then DFS on the reversed graph |
| Articulation points and bridges | DFS | low-link values from discovery times |
| Web crawling, social networks, P2P search | BFS | explore by increasing hop count |
| Maze solving, puzzles, garbage-collector marking | DFS | follow one path, backtrack on dead ends |
A topological order of a directed graph lists its vertices so that for every arc u → v, u appears before v — for example, courses listed so that every prerequisite comes first. It exists if and only if the graph is a DAG (a directed cycle can never be linearised) and is usually not unique. Uses include course planning, build systems such as make, task scheduling, spreadsheet recalculation and instruction scheduling in compilers.
| Dequeue | In-degree updates | Queue afterwards | Order so far |
|---|---|---|---|
| — | — | A B | — |
| A | C: 2 → 1 | B | A |
| B | C: 1 → 0, D: 1 → 0 | C D | A B |
| C | E: 2 → 1 | D | A B C |
| D | E: 1 → 0, F: 2 → 1 | E | A B C D |
| E | F: 1 → 0 | F | A B C D E |
| F | — | empty | A B C D E F |
#include <stdio.h>
#define V 6
int adj[V][V], deg[V], indeg[V];
const char *name = "ABCDEF";
void addArc(int u, int v) { adj[u][deg[u]++] = v; indeg[v]++; } /* u -> v */
int topoSort(int order[]) { /* returns how many vertices were output */
int queue[V], front = 0, rear = 0, k = 0;
for (int v = 0; v < V; v++) if (indeg[v] == 0) queue[rear++] = v;
while (front < rear) {
int u = queue[front++];
order[k++] = u;
for (int i = 0; i < deg[u]; i++)
if (--indeg[adj[u][i]] == 0) queue[rear++] = adj[u][i];
}
return k; /* k < V means a cycle */
}
int main(void) {
addArc(0, 2); addArc(1, 2); addArc(1, 3); /* A->C B->C B->D */
addArc(2, 4); addArc(3, 4); addArc(3, 5); /* C->E D->E D->F */
addArc(4, 5); /* E->F */
int order[V];
int k = topoSort(order);
if (k < V) printf("cycle detected\n");
else {
for (int i = 0; i < k; i++) printf("%c ", name[order[i]]);
printf("\n"); /* A B C D E F */
}
return 0;
}DFS method. Run DFS over all vertices and list them in decreasing finishing time (reverse postorder): a vertex finishes only after everything reachable from it, so it lands before all of them. On this DAG (roots tried alphabetically) the finishing order is F E C A D B, giving the topological order B D A C E F — different from Kahn's A B C D E F, and both are correct. This DAG has 5 valid topological orders in all. Both methods run in O(V + E).
Components. Loop over the vertices; whenever one is still unvisited, start a new BFS or DFS from it and increase a counter. The number of starts is the number of connected components, and each traversal marks exactly one component — O(V + E) in total. In a digraph this gives weakly connected pieces if edge directions are ignored; strongly connected components need Kosaraju's or Tarjan's DFS-based algorithm.
Cycles. In an undirected graph a cycle exists exactly when a traversal meets an already-visited vertex that is not the current vertex's parent (equivalently, a component with k vertices has more than k − 1 edges). In a directed graph, colour vertices white (unvisited), grey (on the recursion stack) and black (finished): an arc into a grey vertex is a back edge and proves a directed cycle.
Bipartite graphs. A graph is bipartite if its vertices split into two sets with every edge crossing between them — like students and the courses they take. A classical result of Dénes Kőnig (1936): a graph is bipartite if and only if it has no cycle of odd length. Trees, even cycles and grids are bipartite; a triangle or any odd cycle is not. Test it by BFS colouring: give the start colour 0, every newly discovered neighbour the opposite colour, and report failure if an edge ever joins two vertices of the same colour.
#include <stdio.h>
#define V 7
int g[V][V]; /* adjacency matrix */
int color[V];
void addEdge(int u, int v) { g[u][v] = g[v][u] = 1; }
int bipartiteFrom(int s) { /* BFS 2-colouring of s's component */
int q[V], front = 0, rear = 0, ok = 1;
color[s] = 0; q[rear++] = s;
while (front < rear) {
int u = q[front++];
for (int v = 0; v < V; v++) if (g[u][v]) {
if (color[v] == -1) { color[v] = 1 - color[u]; q[rear++] = v; }
else if (color[v] == color[u]) ok = 0; /* same colour: odd cycle */
}
}
return ok;
}
int main(void) {
addEdge(0, 1); addEdge(1, 2); addEdge(2, 3); addEdge(3, 0); /* square: even cycle */
addEdge(4, 5); addEdge(5, 6); addEdge(6, 4); /* triangle: odd cycle */
for (int v = 0; v < V; v++) color[v] = -1;
int components = 0;
for (int s = 0; s < V; s++)
if (color[s] == -1) { /* an uncoloured vertex starts a new component */
components++;
printf("component %d is %sbipartite\n", components, bipartiteFrom(s) ? "" : "NOT ");
}
printf("%d components\n", components); /* 1 bipartite, 2 NOT, 2 components */
return 0;
}Try the problem first, then reveal the working one step at a time.
The undirected graph has edges 1–2, 1–3, 2–4, 2–5, 3–6, 3–7, 5–7. Starting from vertex 1 and taking neighbours in increasing order, give the BFS order (with distances) and the DFS order.
Add the arc F → B to the DAG of the topological-sort section (A→C, B→C, B→D, C→E, D→E, D→F, E→F). Run Kahn's algorithm.
Use BFS colouring to decide whether (a) the 6-cycle 1–2–3–4–5–6–1 and (b) the 5-cycle 1–2–3–4–5–1 are bipartite.
A digraph has arcs a→b, a→c, b→c, c→d, d→b. Write its adjacency matrix and adjacency lists, give every in- and out-degree, and name any source or sink.
Can a simple graph have degree sequence (a) 3, 3, 2, 2, 2 (b) 3, 3, 3, 2, 2? If yes, how many edges does it have?
A graph has 10 vertices and 15 edges. Compare the storage of an adjacency matrix and adjacency lists, and state the cost of BFS with each.
How many topological orders does the DAG a→b, a→c, b→d, c→d have? How many does a DAG with 3 vertices and no arcs have?
An undirected graph has edges 0–1, 0–2, 1–3, 2–3, 3–4, 4–5. Perform DFS from vertex 3, always visiting adjacent vertices in decreasing (reverse lexicographic) order.
10 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.