learngraphtheory.org

Guest User

Using app without sign in

Cover of the book Graph Theory Through Problems

Practice book

Graph Theory Through Problems

300 Exercises with Hints, Worked Algorithms and Complete Solutions

By Mohammed Islam Hadjoudj

Learn graph theory by solving problems: 300 exercises, from routine checks to challenging proofs, each with a complete solution.

Available inKindlePaperback

13 chapters

Also by the authorGraph Algorithms for Coding Interviews100 solved interview problems with visual explanations and Python solutions.View on Amazon
Algorithm Selection

Select an algorithm and generate steps to begin visualization

Connected Components Calculator

How many pieces does the graph have?

Splits the graph into its connected pieces, one BFS per piece

Time: O(V + E)
Space: O(V)
Use Case: Is the graph connected? Islands, clusters, image labeling
Showing the example graph for this algorithm.
Algorithm Execution

Select an algorithm and generate steps to begin visualization

About Connected Components

A connected component of an undirected graph is a maximal set of vertices in which every two are joined by a path. Every graph splits into components in exactly one way, and the graph is connected when there is only one. Finding the components is often the first step of a graph algorithm: it tells which vertices can reach each other at all.

How it works

Go through the vertices in order. Whenever a vertex has no label yet, it starts a new component: a breadth-first search from it labels every vertex it reaches with the same component number. A BFS never leaves its component and reaches all of it, so when its queue is empty the component is complete. Each vertex enters the queue once and each edge is looked at from both ends, so the whole run takes O(V + E) time. A depth-first search works the same way, and union-find gives the same answer while edges arrive one by one. For a directed graph, ignoring the directions gives the weakly connected components; strongly connected components need Tarjan's or Kosaraju's algorithm.

Applications

Connected components find isolated groups in social networks, islands in road and power networks, objects in images (connected-component labeling), and clusters of related records in data deduplication. Many algorithms, from minimum spanning forests to graph colouring, run on each component separately. It is one of the first applications of BFS and DFS taught in algorithms courses and a frequent interview question (number of islands, number of provinces).

Pseudocode

Finding connected components is a loop of breadth-first searches. Each vertex that has no label yet starts a new component, and one BFS labels everything reachable from it.

ConnectedComponents(graph):
    k = 0
    for each vertex s, in any order:
        if s has no label:
            k = k + 1
            label[s] = k
            queue = [s]
            while queue is not empty:
                u = queue.removeFirst()
                for each neighbor v of u:
                    if v has no label:
                        label[v] = k
                        queue.addLast(v)
    return k, label

The outer loop guarantees that every vertex is labelled, including isolated ones with no edges, and the inner BFS guarantees that two vertices get the same label exactly when a path joins them. Any traversal works in place of BFS. DFS gives the same partition, and union-find reaches it by processing the edges one at a time.

Worked example, step by step

Label the components of the example this page loads: nine vertices that fall into four pieces of different shapes.

Example graph: Undirected edges A-B, A-C, B-C (a triangle), D-E, E-F (a path), and G-H (a single edge). Vertex I has no edges at all.

  1. Component 1. A has no label, so it starts component 1. The BFS from A reaches B and C directly. B-C is then seen from both ends, but both are already labelled. Component 1 is {A, B, C}, with 3 vertices and 3 edges.
  2. Component 2. The scan moves on. B and C are labelled, so the next unlabelled vertex is D, which starts component 2. The BFS reaches E from D and then F from E. Component 2 is {D, E, F}, with 3 vertices and 2 edges.
  3. Component 3. G starts component 3, and its BFS reaches only H. Component 3 is {G, H}.
  4. Component 4. I is still unlabelled. Its BFS finds no neighbours at all, so it forms component 4 on its own. Only the outer loop over vertices catches it, since no edge mentions I.

There are four components, {A, B, C}, {D, E, F}, {G, H} and {I}. A useful check: a forest with V vertices and E edges has exactly V - E components, which would be 9 - 6 = 3 here. The fourth comes from the triangle, whose third edge closes a cycle instead of joining two pieces. In general the number of components equals V - E plus the number of independent cycles.

Complexity, and where it comes from

Time: O(V + E) · Space: O(V)

Every vertex is enqueued exactly once over the whole run, because it is labelled when it is first reached and never enqueued again, and every adjacency list is scanned once, when its vertex is dequeued. The outer loop adds O(V) checks. The total is O(V + E) with adjacency lists. The label array and the queue are O(V). With union-find, the cost is O(E alpha(V)), where alpha is the inverse Ackermann function, less than 5 for any graph that fits in a computer. That is effectively linear and has the advantage that edges can arrive one at a time.

When to use Connected Components, and when not to

Connectivity questions come in several flavours. Pick the method that fits how the graph is given and what "connected" means for it.

AlternativePrefer it whenCost
DFS labellingSame result as BFS. Natural if you already have a DFS for other purposes, but recursion depth can be a problem on long paths.O(V + E)
Union-findEdges arrive over time, or you only need to ask whether two vertices are connected. It is also the core of Kruskal's algorithm.O(E alpha(V))
Tarjan or KosarajuThe graph is directed and you need strongly connected components, where each vertex can reach every other.O(V + E)
Biconnected componentsYou need to know which pieces survive the loss of any single vertex, not just which pieces are connected.O(V + E)

Common pitfalls

  • Looping over edges instead of vertices. If the outer loop only starts from endpoints of edges, isolated vertices like I are never labelled and the count comes out one too low for each of them.
  • Running it on a directed graph. On a directed graph, BFS from a vertex finds what it can reach, not what can reach it. Ignore edge directions to get weakly connected components, or use Tarjan or Kosaraju for strongly connected ones.
  • Recursive DFS on huge components. A recursive implementation can overflow the call stack on a long path of a few hundred thousand vertices. BFS with an explicit queue, or union-find, avoids the problem.
  • Recomputing after every change. If edges are only added, keep a union-find structure and merge components in near constant time instead of relabelling the whole graph. Deletions are much harder and need dedicated dynamic connectivity structures.

Frequently asked questions

What is a connected component?
A maximal set of vertices in an undirected graph such that every two of them are joined by a path. Every vertex belongs to exactly one component, and an isolated vertex is a component by itself.
How do you find connected components?
Scan the vertices. Whenever one has no label yet, start a BFS or DFS from it and give every vertex it reaches the same new label. The number of labels used is the number of components.
What is the time complexity of finding connected components?
O(V + E) with BFS or DFS on adjacency lists, since every vertex and every edge is processed once. Union-find achieves O(E alpha(V)), which is effectively linear.
What is the difference between connected and strongly connected components?
Connected components are defined for undirected graphs. In a directed graph, a strongly connected component requires a directed path in both directions between any two of its vertices, while a weakly connected component only requires a path when directions are ignored.
Where are connected components used?
In image processing to label regions of pixels, in social network analysis to find isolated groups, in checking whether a network is fully connected after failures, in clustering, and as a first step of many graph algorithms that process each component separately.

Related algorithms: Breadth-First Search, Depth-First Search, Tarjan's SCC Algorithm, Biconnected Components

Interactive Controls

Zoom Controls

47%
Nodes: 9
Edges: 6