MediumDepth-First SearchBreadth-First SearchUnion FindGraph

Connected Components in Undirected Graph

1 approach, code in every language

Problem description

You are given an integer n, representing an undirected graph with nodes labeled from 0 to n - 1, together with a list of undirected edges. Each entry edges[i] = [a, b] means there is an edge connecting node a and node b.

A connected component is a maximal set of nodes such that any two of them are reachable from one another through the edges. Return the total number of connected components in the graph.

Isolated nodes with no incident edges each count as their own component.

Example 1

Input: n = 5, edges = [[0,1],[1,2],[3,4]]

Output: 2

Nodes 0, 1, and 2 are linked into one component, and nodes 3 and 4 form another, so there are 2 components.

Example 2

Input: n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]

Output: 1

Every node is chained together into a single component.

Constraints

  • 1 <= n <= 2000
  • 0 <= edges.length <= n * (n - 1) / 2
  • edges[i].length == 2
  • 0 <= a_i, b_i < n
  • a_i != b_i
  • There are no repeated edges.

After the pattern

Now solve one you haven't seen.

Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.

1,194 problems · 15,062 graded tests · free