Ctrl K

Clusters of Linked Servers

Medium
A data centre has n servers numbered from 0 to n − 1. The n × n matrix links describes the cables: links[i][j] = 1 if servers i and j are wired directly, and 0 otherwise. Every link works both ways, and each server counts as linked to itself. Servers that can reach each other through cables (directly or via other servers) belong to the same cluster. Return the number of clusters.
Example 1
links=[[1, 0, 0, 1], [0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 1]] → 3

Servers 0 and 3 share a cable and form one cluster, while servers 1 and 2 stand alone. That makes three clusters.

Example 2
links=[[1, 1, 0], [1, 1, 1], [0, 1, 1]] → 1

Server 0 is not wired to server 2 directly, but both are wired to server 1, so the whole network is one cluster.

Example 3
links=[[1]] → 1
Constraints
  • 1 ≤ n ≤ 200
  • links is an n × n matrix of 0s and 1s
  • links[i][i] = 1
  • links[i][j] = links[j][i]
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsDo the Links Form a Tree MediumIsolated Groups in a Network MediumRatio Chain Queries MediumThe Extra Cable MediumSplit Into Two Teams Medium
loading Python…
Input
links=[[1, 0, 0, 1], [0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 1]]
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 60 tests on the server, hidden ones included.