8.3Graph Applications
Connected components
A graph does not have to be in one piece. Two groups of friends who have never met in a social network, two islands with no road between them or a network with a cut cable are separate pieces of the same graph. Each piece is called a connected component. In this lesson you write a function that gives every vertex the number of its component; the tool is depth-first search.
- What a connected component is and how many a graph can have
- How to number the components by starting a new DFS from every unmarked vertex
- Why the work takes O(V + E) time
1Idea
A DFS that starts at a vertex visits every vertex reachable from it and stops there. The vertices it visits are exactly the component of that vertex. If unmarked vertices are left, they are in another component; you start a new DFS from the first unmarked one.
So the function has two parts. mark(g, u, id, comp) writes the component number on the vertex and calls itself for every unmarked neighbour; this is the same recursion as in the DFS lesson, except that a comp array holding numbers replaces the visited array. components walks over all the vertices in order; every vertex where it sees -1 is the first vertex of a new component.
In the end, whether two vertices are in the same component takes one comparison: comp[u] == comp[v]. If the graph has one component, that is if the function returns 1, the graph is called connected.
BFS gives the same result instead of DFS: both visit each vertex reachable from the start once. Components are this simple only in an undirected graph. In a directed graph the set of vertices that "can reach each other" is called a strongly connected component, and finding it needs more involved algorithms.
2Step by step
The drawing shows an undirected graph with 7 vertices. The c value under a vertex is its number in the comp array. The orange vertex is the one being marked; the mark calls are shown under the drawing.
- Start. Every vertex has number -1 and
countis 0. - 0 is unmarked: a new component starts.
mark(0)is called and 0 gets number 0. - The first neighbour of 0, 1, is unmarked:
mark(1). 1 is in component 0 too. - The neighbours of 1 are 0 and 3. 0 is marked, 3 is not:
mark(3). - The neighbours of 3 are 1 and 2. 1 is marked, 2 is not:
mark(2). The neighbours of 2, 0 and 3, are both marked. - The calls return one by one. Component 0 is done: 0, 1, 2, 3.
countis now 1. - The loop finds 1, 2 and 3 marked and skips them. 4 is unmarked: component 1 starts.
- The only neighbour of 4 is 5:
mark(5). Component 1: 4 and 5. countis now 2. 5 is skipped. 6 is unmarked but has no neighbours: component 2 on its own.- The loop is over. The function returns 3: the graph has three connected components.
#define MAX 8 struct Node { int data; struct Node* next;}; struct Graph { int n; bool directed; struct Node* adj[MAX];}; void mark(struct Graph* g, int u, int id, int comp[]) { comp[u] = id; // u is in this component for (struct Node* p = g->adj[u]; p != NULL; p = p->next) if (comp[p->data] == -1) // an unmarked neighbour mark(g, p->data, id, comp);} int components(struct Graph* g, int comp[]) { for (int u = 0; u < g->n; u++) comp[u] = -1; int count = 0; for (int u = 0; u < g->n; u++) if (comp[u] == -1) { // a new component starts mark(g, u, count, comp); count++; } return count;}class Node { int data; Node next; Node(int data) { this.data = data; }} class ListGraph { int n; boolean directed; Node[] adj; ListGraph(int n, boolean directed) { this.n = n; this.directed = directed; adj = new Node[n]; }} void mark(ListGraph g, int u, int id, int[] comp) { comp[u] = id; // u is in this component for (Node p = g.adj[u]; p != null; p = p.next) if (comp[p.data] == -1) // an unmarked neighbour mark(g, p.data, id, comp);} int components(ListGraph g, int[] comp) { for (int u = 0; u < g.n; u++) comp[u] = -1; int count = 0; for (int u = 0; u < g.n; u++) if (comp[u] == -1) { // a new component starts mark(g, u, count, comp); count++; } return count;}class Node: def __init__(self, data): self.data = data self.next = None class ListGraph: def __init__(self, n, directed=False): self.n = n self.directed = directed self.adj = [None] * n def mark(g, u, id_, comp): comp[u] = id_ # u is in this component p = g.adj[u] while p is not None: if comp[p.data] == -1: # an unmarked neighbour mark(g, p.data, id_, comp) p = p.next def components(g, comp): for u in range(g.n): comp[u] = -1 count = 0 for u in range(g.n): if comp[u] == -1: # a new component starts mark(g, u, count, comp) count += 1 return countThe snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
Every vertex is marked once and every adjacency list is read once: O(V + E) for V vertices and E edges.
The comp array holds V elements. In the worst case the recursion goes V levels deep.
The outer loop looks at every vertex but does nothing at marked ones. Since all the DFS runs together visit each vertex exactly once, the total work stays O(V + E) however many components there are.
4Common mistake
A common mistake is starting a DFS only from vertex 0 and stopping:
mark(g, 0, 0, comp);return 1; // the other components are forgottenThis code is right only when the graph is in one piece. Whether unmarked vertices are left must always be checked with the outer loop. Another mistake is mixing the number up with a visited flag and treating 0 as "not visited": the first component's number is 0 too, which is why the starting value is -1.
5Try it
An undirected graph with 8 vertices has the edges 0-1, 1-2, 3-4 and 5-6. How many connected components does it have?
The answer is B. {0, 1, 2}, {3, 4}, {5, 6} and {7}, which has no edges: four components. A vertex with no edges is a component on its own.
Show the answer
The answer is B. {0, 1, 2}, {3, 4}, {5, 6} and {7}, which has no edges: four components. A vertex with no edges is a component on its own.
Why does finding the components take O(V + E) time?
The answer is B. A DFS starts only at unmarked vertices. All the DFS runs together visit each vertex once and read each adjacency list once.
Show the answer
The answer is B. A DFS starts only at unmarked vertices. All the DFS runs together visit each vertex once and read each adjacency list once.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.