Connected Groups (Friend Circles)
viaLeetCode
Problem Given an n x n binary relation matrix as strings (related[i][j] = '1' means i knows j), with transitive friendship, count the number of connected groups (friend circles).
Input / Output
- Input: string array related (n rows of n chars).
- Output: number of groups.
Constraints
- n <= 300 → O(n^2) matrix scan is fine.
Example
- ["110","110","001"] → 2 (persons 0–1, and person 2).
Expected approach
- Union-Find over persons: for each pair (i, j) with '1', union them; answer = number of distinct roots. With rank/path compression, O(n^2 α(n)). DFS/BFS over the matrix rows counting launches is equally valid. Matrix-vs-adjacency-list framing and the transitivity ("components, not edges") observation are what's being checked.
asked …