Count Islands of Mutual Acquaintances in a Matrix
Trees & GraphsAuto-graded · 15 test casesLast updated
Count connected components in an undirected graph given as a symmetric adjacency matrix, without modifying the input, using graph traversal or union-find.
Circles of Acquaintances
A community has n members, numbered 0 through n - 1. Their relationships are described by a square matrix links of size n x n.
links[i][j] == 1means membersiandjknow each other directly.links[i][j] == 0means they do not know each other directly.
Knowing someone is mutual: if i knows j, then j knows i. Circles also extend through chains of acquaintance: if A knows B and B knows C, then A, B, and C are all in the same circle, even if A and C do not know each other directly.
A circle is therefore a maximal set of members in which any two can be linked through a chain of direct acquaintances. Every member belongs to exactly one circle, and a member who knows nobody else forms a circle alone.
Return the number of distinct circles in the community.
Your function must not modify the input matrix.
Input
links: a list ofnlists, each containingnintegers (0or1), forming a symmetric matrix.
Output
- An integer: the number of circles.
Constraints
1 <= n <= 200, wheren == len(links)andlen(links[i]) == nfor everyilinks[i][j]is either0or1links[i][i] == 1for everyilinks[i][j] == links[j][i]for alli,j- The input must be treated as read-only
Examples
Example 1
Input: count_circles([[1, 1, 0], [1, 1, 0], [0, 0, 1]])
Output: 2
Example 2
Input: count_circles([[1, 0, 0, 1], [0, 1, 1, 0], [0, 1, 1, 0], [1, 0, 0, 1]])
Output: 2
Hints
Hint 1
Think of each member as a node and each 1 in the matrix as an undirected edge. A circle is then a connected component.
Hint 2
Scan members in order. Whenever you reach one you have not seen yet, you have found a new circle; then explore everyone reachable from them and mark them all as seen.
Hint 3
Keep a separate seen array instead of editing the matrix. Using an explicit stack or queue avoids deep recursion. Alternatively, union-find starting with n sets and decrementing on each successful merge also works.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat each member as a graph node and each 1 in the matrix as an undirected edge. A circle is exactly a connected component, so the answer is the number of connected components.
- Keep a
seenarray of sizen, initially allFalse. - Loop over members
0..n-1. If a member has not been seen, a new circle has been found: increment the counter. - From that member, run an iterative depth-first search (explicit stack). Every member reachable through acquaintance links is marked as seen, so they are never counted again.
Members are marked as seen when they are pushed onto the stack, so each member enters the stack at most once.
Why it is correct
- Each circle is counted at least once: the outer loop reaches every member, and the first member of a circle that it reaches is unseen, because no member outside the circle can reach into it.
- Each circle is counted at most once: the traversal from the first member marks everyone in its component before the outer loop continues, so no other member of that circle triggers another increment.
- The input matrix is never written to; only the separate
seenlist is modified. - Diagonal
1s are harmless since a member is already seen when its own row is scanned.
An explicit stack is used instead of recursion so that long chains of acquaintances cannot hit Python's recursion limit.
Complexity
- Time: O(n^2), since each member is popped once and its row of length
nis scanned. - Space: O(n) extra for the
seenarray and the stack.
Alternative
Union-find: start with n components, and for every links[i][j] == 1 with i < j, union the two members, decrementing the count whenever two different roots are merged. This runs in O(n^2 * alpha(n)) time and O(n) space.
Reference solution
from typing import List
def count_circles(links: List[List[int]]) -> int:
n = len(links)
seen = [False] * n
circles = 0
for start in range(n):
if seen[start]:
continue
circles += 1
seen[start] = True
stack = [start]
while stack:
cur = stack.pop()
row = links[cur]
for other in range(n):
if row[other] and not seen[other]:
seen[other] = True
stack.append(other)
return circles