Number of Connected Components
You have n nodes labelled 0 to n - 1 and an array edges, where edges[i] = [a, b] is an undirected edge between nodes a and b.
A connected component is a group of nodes in which every node can reach every other node by following edges, and which no outside node can reach. A node with no edges at all is a component by itself.
Return the number of connected components in the graph.
Constraints
1 <= n <= 20000 <= edges.length <= 5000edges[i].length === 2,0 <= a, b < nanda !== b- No edge appears twice.
Examples
Example 1
Input: n = 5, edges = [[0,1],[1,2],[3,4]] Output: 2
0, 1 and 2 are linked into one piece and 3-4 is another: 2 components.
Example 2
Input: n = 6, edges = [[0,1],[1,2],[2,0],[3,4]] Output: 3
The edge 2-0 closes a loop inside an existing piece, so it merges nothing. The pieces are {0, 1, 2}, {3, 4} and the lone node 5: 3 components.
Example 3
Input: n = 4, edges = [] Output: 4
With no edges every node is its own component.
JavaScript you'll use: Classes for data structures Arrays: create, read, update
/**
* @param {number} n
* @param {number[][]} edges
* @return {number}
*/
function countComponents(n, edges) {
}
Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.