← Graph Exploration

Micro-Drill #264 — Count connected components

Graph Exploration Target: 15s

Loop over all nodes, DFS/BFS from unvisited ones, increment count each time. Works on adjacency list or matrix.

visited = set()
count = 0
for node in range(n):
    if node not in visited:
        count += 1
        stack = [node]
        while stack:
            cur = stack.pop()
            if cur in visited: continue
            visited.add(cur)
            stack.extend(graph[cur])

Type it from memory. Go.

Practice Problems

Related Coding Drills

← Micro #263 Micro #265 →