leetcode 547. 朋友圈

题解

广度搜索的思想,如果某学生还没有出现在visited数组中,则朋友圈数count加一,并加入队列queue,然后搜索是朋友关系的同学加入queue

示例代码(go)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
func findCircleNum(M [][]int) int {
students := len(M[0])
visited := make([]int, students)
count := 0
for i := 0; i < students; i++ {
if visited[i] == 0 {
count++
visited[i] = 1
queue := []int{i}
for len(queue) > 0 {
for j := 0; j < students; j++ {
if visited[j] == 0 && M[queue[0]][j] == 1 {
visited[j] = 1
queue = append(queue, j)
}
}
queue = queue[1:]
}
}
}
return count
}