2368. 受限条件下可到达节点的数目

2368. 受限条件下可到达节点的数目

解法一: 深度优先遍历

go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
func reachableNodes(n int, edges [][]int, restricted []int) int {
tree := make(map[int][]int)
for _, edge := range edges {
tree[edge[0]] = append(tree[edge[0]], edge[1])
tree[edge[1]] = append(tree[edge[1]], edge[0])
}
set := make(map[int]bool, len(restricted))
for _, num := range restricted {
set[num] = true
}
return dfs(0, -1, tree, set)
}

func dfs(cur, parent int, tree map[int][]int, set map[int]bool) int {
ans := 1
for _, next := range tree[cur] {
if next != parent && !set[next] {
ans += dfs(next, cur, tree, set)
}
}
return ans
}
作者

wuhunyu

发布于

2024-03-02

更新于

2025-01-15

许可协议