Skip to content

Commit 2ff6bd2

Browse files
authored
Create 547. Friend Circles.md
1 parent 3ddd6d0 commit 2ff6bd2

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is a direct friend of B, and B is a direct friend of C, then A is an indirect friend of C. And we defined a friend circle is a group of students who are direct or indirect friends.
2+
3+
Given a N*N matrix M representing the friend relationship between students in the class. If M[i][j] = 1, then the ith and jth students are direct friends with each other, otherwise not. And you have to output the total number of friend circles among all the students.
4+
5+
Example 1:
6+
7+
Input:
8+
[[1,1,0],
9+
[1,1,0],
10+
[0,0,1]]
11+
Output: 2
12+
Explanation:The 0th and 1st students are direct friends, so they are in a friend circle.
13+
The 2nd student himself is in a friend circle. So return 2.
14+
15+
Example 2:
16+
17+
Input:
18+
[[1,1,0],
19+
[1,1,1],
20+
[0,1,1]]
21+
Output: 1
22+
Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends,
23+
so the 0th and 2nd students are indirect friends. All of them are in the same friend circle, so return 1.
24+
25+
Constraints:
26+
27+
1 <= N <= 200
28+
M[i][i] == 1
29+
M[i][j] == M[j][i]
30+
31+
```Python
32+
class Solution:
33+
def findCircleNum(self, M: List[List[int]]) -> int:
34+
N = len(M)
35+
visited = [0] *N
36+
count = 0
37+
queue = []
38+
39+
arr = [i for i in range(N)]
40+
while(len(arr) > 0):
41+
# Starting a new cycle
42+
queue.append(arr.pop(0))
43+
while len(queue) > 0:
44+
i = queue.pop(0)
45+
if visited[i] == 0:
46+
count +=1
47+
visited[i] = 1
48+
# Check all neighboring nodes, adding to queueu
49+
for j, value in enumerate(M[i]):
50+
if value == 1 and visited[j] == 0:
51+
visited[j] = 1
52+
queue.append(j)
53+
arr.remove(j)
54+
if i in arr:
55+
arr.remove(i)
56+
57+
return count
58+
59+
```

0 commit comments

Comments
 (0)