Problem · Graph
Connected Groups
Learn this problemProblem statement
You are given a square binary matrix related. Each row and column represents one person at the same party.
related[i][j] == 1means that personiand personjhave a direct connection.related[i][j] == 0means that they do not have a direct connection.
Connections are transitive. If person a is connected to person b, and person b is connected to person c, then all three people belong to the same group.
Return the number of distinct groups. If related is empty, return 0.
Function
countConnectedGroups(related: int[][]) → intExamples
Example 1
related = [[1,1,0],[1,1,1],[0,1,1]]return = 1Person 0 is directly connected to person 1, and person 1 is directly connected to person 2. Transitivity places all three people in one group.
Example 2
related = [[1,0,0],[0,1,1],[0,1,1]]return = 2Person 0 forms one group. Persons 1 and 2 form the other group.
Example 3
related = [[1,0,1,0],[0,1,0,1],[1,0,1,0],[0,1,0,1]]return = 2Persons 0 and 2 form one group, while persons 1 and 3 form the other. Group members do not need consecutive indices.
Constraints
- Let
n = related.length. 0 <= n <= 1000.relatedhas exactlynrows, and every row has exactlynentries.- Every entry in
relatedis either0or1. related[i][i] == 1for every valid indexi.related[i][j] == related[j][i]for all valid indicesiandj.