Number of Connected Components

Given n nodes and an undirected edge list, return the number of connected components in the graph. Pattern focus: Connected. A graph component is a maximal set of nodes reachable from one another.

Input Format

n = number of nodes, edges = undirected edges

Output Format

number of connected components

Constraints

  • 1 <= input size <= 10^5
  • -10^9 <= numeric values <= 10^9
  • n, edges must satisfy the format described in inputFormat.

Examples

Example 1:

Input:

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

Output:

2

Explanation:

Nodes {0,1,2} and {3,4} form two components.

Example 2:

Input:

n = 3
edges = [[0,1]]

Output:

2
Loading...
Number of Connected Components