Connected components

A connected component is a group of vertices that can all reach each other. Your program counts the components of a graph and measures their sizes.

What to build

A program that prints the number of connected components and their sizes.

Requirements

  • Read n and m, then m edges u v of an undirected graph on the vertices 1 to n.
  • Print components: and the number of connected components. A vertex with no edges is a component of its own.
  • Print sizes: and the sizes of the components from largest to smallest, separated by spaces.

Input

The first line has n and m. Each of the next m lines has an edge.

Output

Two lines.

Constraints

1 ≤ n ≤ 30; 0 ≤ m ≤ 60.

Example

Input:

5 3
1 2
2 3
4 5

Output:

components: 2
sizes: 3 2

Why it works

One search from a vertex reaches exactly its own component and marks all of it, so the next unvisited vertex belongs to a different component. The number of searches started is therefore the number of components, and the number of vertices each reaches is its size.

Examples

Example 1 · Input
5 3
1 2
2 3
4 5
Expected output
components: 2
sizes: 3 2
Example 2 · Input
4 0
Expected output
components: 4
sizes: 1 1 1 1

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Keep a visited set. For each vertex not yet visited, start a search and count the vertices it reaches.

Hint 2

Either BFS or DFS works; you only need the size of each group.

Hint 3

Print the sizes from largest to smallest.

Solution

Show one correct solution (try it yourself first)
n, m = map(int, input().split())
adj = {v: [] for v in range(1, n + 1)}
for _ in range(m):
    u, v = map(int, input().split())
    adj[u].append(v)
    adj[v].append(u)
seen = set()
sizes = []
for s in range(1, n + 1):
    if s in seen:
        continue
    seen.add(s)
    stack = [s]
    size = 0
    while stack:
        v = stack.pop()
        size += 1
        for w in adj[v]:
            if w not in seen:
                seen.add(w)
                stack.append(w)
    sizes.append(size)
sizes.sort(reverse=True)
print("components:", len(sizes))
print("sizes:", *sizes)

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Searching a graph: BFS and DFS →