Number of Connected Components in an Undirected Graph
Real-world version: Counting Separate Clusters of WorkshopsThe statement here is our own: the same inputs, outputs and technique.
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 starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def count_components(n: int, links: list[list[int]]) -> int:public int countComponents(int n, int[][] links)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 17 test cases: 17 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's