Skip to main content
1 of 4
arshajii
  • 2.2k
  • 12
  • 21

Determine number of unconnected components

You are given a graph represented through an adjacency list. For example, the input

1-2 2-3 3-4 4-1

would correspond to the graph with nodes 1, 2, 3 and 4, where 1 is connected to 2, 2 is connected to 3, 3 is connected to 4, and 4 is connected to 1 (forming a square).

The task is to determine the number of of unconnected components of the graph represented by an inputted adjacency list. An "unconnected component" is a set of nodes from which there is no path to any other node that is not in the set. So, for instance, a lone node with no connections would be considered an unconnected component.

Language of your choice - shortest code possible.

arshajii
  • 2.2k
  • 12
  • 21