Problem · Graph
Connected Groups
Learn this problemProblem statement
Given an N by N symmetric binary matrix related, treat each index as one member. When related[i][j] == 1, members i and j are directly related.
Membership is transitive: members connected through any chain of direct relationships belong to the same group. Every member belongs to exactly one group, including an isolated member.
Return the number of connected groups.
Function
countConnectedGroups(related: int[][]) → intExamples
Example 1
related = [[1,1,0],[1,1,0],[0,0,1]]return = 2Members 0 and 1 form one group, while member 2 is isolated and forms the second group.
Example 2
related = [[1,0,0,0],[0,1,1,0],[0,1,1,1],[0,0,1,1]]return = 2Member 0 is one group. Members 1, 2, and 3 form the other because 1 reaches 3 through 2.