Data structures · 14 / 15 Exercise Hard

Connected components

Objective

Create a Python program that counts the connected components of an undirected graph (groups of nodes that can reach each other) with a depth-first search (DFS) that uses a stack.

Instructions

  • The first line contains n m (nodes, from 1 to n) and m (edges). The next m lines each contain an edge a b.
  • Go through nodes 1 to n; each time you find an unvisited one, it is a new component: explore it entirely with a stack and count its nodes.
  • Show Components: k and Sizes: s1 s2 ... with the component sizes, from largest to smallest, separated by spaces.
Input
7 5
1 2
2 3
4 5
5 6
4 6
Output
Components: 3
Sizes: 3 3 1

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise