10323. Number of Connected Components in an Undirected Graph

You are given nodeCount nodes labeled from 0 to nodeCount - 1 and a collection of undirected edges, where each edge connects two nodes.
Edges are actually list of string and you will have to parse each row to extract connected nodes.

Write a method to determine how many separate connected groups (components) there are in the undirected graph.

Examples

Example 1:
Input: nodeCount = 6, links = ["0 2", "1 2", "3 5"]
Graph structure:
0 1 3
\ / |
2 5

Nodes 0-1-2 are connected, 3-5 are connected, and node 4 is isolated.
Output: 3
Explanation: There are three groups: {0,1,2}, {3,5}, and {4}.

Example 2:
Input: nodeCount = 4, links = ["0 1", "1 2", "2 3"]
Graph structure:
0-1-2-3
Output: 1
Explanation: All nodes are part of a single connected component.

Example 3:
Input: nodeCount = 3, links = []
Output: 3
Explanation: Each node is isolated, so there are 3 separate components.

Constraints

  • 1 <= nodeCount <= 104
  • 0 <= links.length <= 2 * 104
  • links[i].length == 2
  • 0 <= links[i][0], links[i][1] < nodeCount
  • There are no duplicate edges or self-loops in links.
  • Each edge is undirected; [a,b] is the same as [b,a].




Please use Laptop/Desktop or any other large screen to add/edit code.