KatInterview

Count Islands of Mutual Acquaintances in a Matrix

Trees & GraphsAuto-graded · 15 test cases
MediumAuto-gradedTrees & Graphsgraphconnected-componentsdfs

Last 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] == 1 means members i and j know each other directly.
  • links[i][j] == 0 means 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 of n lists, each containing n integers (0 or 1), forming a symmetric matrix.

Output

  • An integer: the number of circles.

Constraints

  • 1 <= n <= 200, where n == len(links) and len(links[i]) == n for every i
  • links[i][j] is either 0 or 1
  • links[i][i] == 1 for every i
  • links[i][j] == links[j][i] for all i, 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.