LC.P2368[受限条件下可到达节点的数目]

方法一:DFS

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
class Solution {

List<Integer>[] g;
int ans;
Set<Integer> set;

public int reachableNodes(int n, int[][] edges, int[] restricted) {
g = new List[n];
Arrays.setAll(g, k -> new ArrayList<>());
for (int[] e : edges) {
int a = e[0], b = e[1];
g[a].add(b);
g[b].add(a);
}
set = new HashSet<>();
for (int e : restricted) {
set.add(e);
}
dfs(0, -1);
return ans;
}

private void dfs(int x, int pa) {
++ans;
for (int y : g[x]) {
if (y != pa) {
if (set.contains(y)) continue;
dfs(y, x);
}
}
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$

方法二:优化

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
class Solution {

List<Integer>[] g;

public int reachableNodes(int n, int[][] edges, int[] restricted) {
boolean[] isRestricted = new boolean[n];
for (int x : restricted) {
isRestricted[x] = true;
}
g = new List[n];
Arrays.setAll(g, k -> new ArrayList<>());
for (int[] e : edges) {
int a = e[0], b = e[1];
// 都不受限才连边
if (!isRestricted[a] && !isRestricted[b]) {
g[a].add(b);
g[b].add(a);
}
}
return dfs(0, -1);
}

private int dfs(int x, int pa) {
int ans = 1;
for (int y : g[x]) {
if (y != pa) {
ans += dfs(y, x);
}
}
return ans;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$