981. Count Connected Components in Undirected Graph

EasyGraphsDFSGraph

Given an undirected graph with n nodes and a list of edges, return the number of connected components (maximal groups of mutually reachable nodes; isolated nodes count as their own component). The input is JSON {n, edges}.

Input: JSON {n, edges}.

Output: Integer — the number of connected components.

Examples

Example 1
Input: {"n":5,"edges":[[0,1],[2,3]]}
Output: 3
Explanation: Components {0,1},{2,3},{4}.
Example 2
Input: {"n":1,"edges":[]}
Output: 1
Explanation: Single node.
Example 3
Input: {"n":3,"edges":[[0,1],[1,2]]}
Output: 1
Explanation: All connected.

Constraints

Asked by

TCSInfosysWiproCognizantCapgemini
Solve this problem in the editor →