All problems
0989MediumDepth-First SearchBreadth-First SearchUnion-FindGraph Theory

Counting Separate Clusters of Workshops

Tracked in this browser only
Write code

Trains the technique from

LeetCode 323Number of Connected Components in an Undirected Graph

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A campus has n workshops numbered 0 through n - 1. Each entry links[i] = [a, b] is a walkway between workshop a and workshop b that may be used in either direction.

Two workshops belong to the same cluster when some run of walkways leads from one to the other. Every workshop belongs to a cluster, even one no walkway touches.

Return how many clusters the campus has.

Examples

Example 1

Input
n = 6, links = [[0, 1], [1, 2], [4, 5]]
Output
3

Workshops 0, 1 and 2 hang together through two walkways, 4 and 5 make a pair, and 3 stands alone, which is three clusters.

Example 2

Input
n = 6, links = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]]
Output
1

The walkways form one long run through every workshop, so the whole campus is a single cluster.

Example 3

Input
n = 4, links = [[0, 1], [1, 2], [0, 2]]
Output
2

The third walkway joins a pair already linked through workshop 1, so it merges nothing. Workshops 0, 1 and 2 make one cluster and workshop 3 makes another.

Constraints

  • 1 <= n <= 2000
  • 1 <= links.length <= 5000
  • links[i].length == 2
  • 0 <= links[i][j] <= n - 1
  • The two ends of a walkway are different workshops.
  • No walkway is listed twice.

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def count_components(n: int, links: list[list[int]]) -> int:
Java
public int countComponents(int n, int[][] links)
September 7
Apply