Friend Circles
There areNstudents in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is adirectfriend of B, and B is adirectfriend of C, then A is anindirectfriend of C. And we defined a friend circle is a group of students who are direct or indirect friends.
Given aN*NmatrixMrepresenting the friend relationship between students in the class. If M[i][j] = 1, then the ithand jthstudents aredirectfriends with each other, otherwise not. And you have to output the total number of friend circles among all the students.
Example 1:
Input:
[[1,1,0],
[1,1,0],
[0,0,1]]
Output:
2
Explanation:
The 0
th
and 1
st
students are direct friends, so they are in a friend circle.
The 2
nd
student himself is in a friend circle. So return 2.Example 2:
Note:
N is in range [1,200].
M[i][i] = 1 for all students.
If M[i][j] = 1, then M[j][i] = 1.
Union Find
union里面f[x]=y不要再反顺序了。
DFS
不能看成Matrix4个方向连通问题,而是每个人单独dfs
需要visited set记录每个人是否遍历过
BFS
Last updated
Was this helpful?