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); } } } }
|