-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
55 lines (49 loc) · 1 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package main
// dfs
// time complexity: O(n^2)
// space complexity: O(n)
func findCircleNum(isConnected [][]int) int {
visited := make(map[int]bool, len(isConnected))
var dfs func(int)
dfs = func(node int) {
visited[node] = true
for i := 0; i < len(isConnected); i++ {
if isConnected[node][i] == 1 && !visited[i] {
dfs(i)
}
}
}
var provinces int
for i := 0; i < len(isConnected); i++ {
if !visited[i] {
provinces++
dfs(i)
}
}
return provinces
}
// bfs
// time complexity: O(n)
// space complexity: O(n)
func findCircleNum2(isConnected [][]int) int {
visited := make(map[int]bool, len(isConnected))
queue := []int{}
provinces := 0
for i := 0; i < len(isConnected); i++ {
if !visited[i] {
provinces++
queue = append(queue, i)
}
for len(queue) > 0 {
curr := queue[0]
queue = queue[1:]
visited[curr] = true
for j := 0; j < len(isConnected); j++ {
if isConnected[curr][j] == 1 && !visited[j] {
queue = append(queue, j)
}
}
}
}
return provinces
}