2316. 统计无向图中无法互相到达点对数

2316. 统计无向图中无法互相到达点对数

解法一: 深度优先遍历

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
func countPairs(n int, edges [][]int) int64 {
grip := make([][]int, n)
for i := 0; i < n; i++ {
grip[i] = []int{}
}
for _, edge := range edges {
grip[edge[0]] = append(grip[edge[0]], edge[1])
grip[edge[1]] = append(grip[edge[1]], edge[0])
}
visit := make([]bool, n)
var ans int64
var total int64
for i := 0; i < n; i++ {
size := dfs(i, grip, visit)
ans += size * total
total += size
}
return ans
}

func dfs(num int, grip [][]int, visit []bool) int64 {
if visit[num] {
return 0
}
visit[num] = true
var size int64 = 1
for _, num2 := range grip[num] {
size += dfs(num2, grip, visit)
}
return size
}

image-20231021081547435

作者

wuhunyu

发布于

2023-10-21

更新于

2023-10-21

许可协议