Graphs Traversing a graph
450. Number of Connected Components in an Undirected Graph
You are given an undirected graph with n vertices, numbered from 0 to n - 1. Each pair [u, v] in
edges is an edge between vertices u and v, and it can be used in both directions.
A connected component is a group of vertices in which every vertex can reach every other one along edges, and that no edge joins to a vertex outside the group. A vertex with no edges is a component on its own.
Return the number of connected components in the graph.
Example 1
Input: n = 7
edges = [[0, 2],
[5, 1],
[2, 4],
[3, 6],
[4, 0]]
3Explanation: Vertices 0, 2 and 4 form one component, joined in a cycle. Vertices 1 and 5 form the second, and 3 and 6 the third.
Example 2
Input: n = 5, edges = [[3, 1]]
4Explanation: Vertices 1 and 3 form one component. Vertices 0, 2 and 4 have no edges, so each is a component on its own.
Example 3
Input: n = 1, edges = []
1Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ n ≤ 1050 ≤ edges.length ≤ 2 × 105edges[i].length == 20 ≤ ui, vi < nui ≠ vi- No edge appears twice:
[u, v]and[v, u]are the same edge.
Clarifying questions
What you would ask an interviewer before writing any code.