People in a network are joined by friendships. A group is everyone who can reach each other through friends. Count the groups.
What to build
A program that counts the connected components of an undirected graph.
Requirements
- Nodes are numbered 0 to n − 1; each edge joins two nodes in both directions.
- Print the number of connected components.
Input
The first line has n and m. Each of the next m lines has an edge a b.
Output
The number of components.
Constraints
1 ≤ n ≤ 10⁴; 0 ≤ m ≤ 5 × 10⁴.
Example
Input:
5 3
0 1
1 2
3 4
Output:
2
Why it works
Starting a search from an unvisited node reaches exactly its component, so the number of searches started is the number of components. Every node and edge is looked at once: O(n + m).
Examples
5 3 0 1 1 2 3 4
2
4 0
4
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Build an adjacency list: for each node, the list of its neighbours.
Hint 2
For each node not visited yet, count one group and visit everything reachable from it (a stack or a queue).
Hint 3
Nodes with no edges are groups of their own.
Solution
Show one correct solution (try it yourself first)
n, m = map(int, input().split())
adj = [[] for _ in range(n)]
for _ in range(m):
a, b = map(int, input().split())
adj[a].append(b)
adj[b].append(a)
seen = [False] * n
groups = 0
for s in range(n):
if not seen[s]:
groups += 1
seen[s] = True
stack = [s]
while stack:
u = stack.pop()
for v in adj[u]:
if not seen[v]:
seen[v] = True
stack.append(v)
print(groups)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step