|
1 | 1 | package g2301_2400.s2368_reachable_nodes_with_restrictions; |
2 | 2 |
|
3 | 3 | // #Medium #Array #Tree #Graph #Hash_Table #Depth_First_Search #Breadth_First_Search |
4 | | -// #2022_08_15_Time_88_ms_(42.86%)_Space_201.1_MB_(14.29%) |
| 4 | +// #2022_08_16_Time_59_ms_(85.71%)_Space_89.6_MB_(85.71%) |
5 | 5 |
|
6 | | -import java.util.LinkedList; |
| 6 | +import java.util.ArrayDeque; |
| 7 | +import java.util.ArrayList; |
| 8 | +import java.util.List; |
| 9 | +import java.util.Queue; |
7 | 10 |
|
| 11 | +@SuppressWarnings("unchecked") |
8 | 12 | public class Solution { |
9 | 13 | public int reachableNodes(int n, int[][] edges, int[] restricted) { |
10 | | - LinkedList<Integer>[] adj = new LinkedList[n]; |
11 | | - for (int i = 0; i < n - 1; i++) { |
12 | | - if (adj[edges[i][0]] == null) { |
13 | | - LinkedList<Integer> source = new LinkedList<>(); |
14 | | - source.add(edges[i][1]); |
15 | | - adj[edges[i][0]] = source; |
16 | | - } else { |
17 | | - adj[edges[i][0]].add(edges[i][1]); |
18 | | - } |
19 | | - if (adj[edges[i][1]] == null) { |
20 | | - LinkedList<Integer> dest = new LinkedList<>(); |
21 | | - dest.add(edges[i][0]); |
22 | | - adj[edges[i][1]] = dest; |
23 | | - } else { |
24 | | - adj[edges[i][1]].add(edges[i][0]); |
25 | | - } |
| 14 | + List<Integer>[] graph = new ArrayList[n]; |
| 15 | + for (int i = 0; i < n; i++) { |
| 16 | + graph[i] = new ArrayList<>(); |
26 | 17 | } |
27 | | - boolean[] visited = new boolean[n]; |
28 | | - for (int res : restricted) { |
29 | | - visited[res] = true; |
| 18 | + for (int[] edge : edges) { |
| 19 | + int src = edge[0]; |
| 20 | + int dest = edge[1]; |
| 21 | + graph[src].add(dest); |
| 22 | + graph[dest].add(src); |
30 | 23 | } |
31 | | - int count = 1; |
| 24 | + Queue<Integer> q = new ArrayDeque<>(); |
| 25 | + boolean[] visited = new boolean[n]; |
| 26 | + q.offer(0); |
32 | 27 | visited[0] = true; |
33 | | - return countReachableNodes(0, adj, visited, count); |
34 | | - } |
35 | | - |
36 | | - private int countReachableNodes( |
37 | | - int source, LinkedList<Integer>[] adj, boolean[] visited, int count) { |
38 | | - for (int neighbour : adj[source]) { |
39 | | - if (!visited[neighbour]) { |
40 | | - visited[neighbour] = true; |
41 | | - count = countReachableNodes(neighbour, adj, visited, ++count); |
| 28 | + for (int node : restricted) { |
| 29 | + visited[node] = true; |
| 30 | + } |
| 31 | + int ans = 0; |
| 32 | + while (!q.isEmpty()) { |
| 33 | + int vertex = q.poll(); |
| 34 | + ans++; |
| 35 | + for (int neighbour : graph[vertex]) { |
| 36 | + if (!visited[neighbour]) { |
| 37 | + q.offer(neighbour); |
| 38 | + visited[neighbour] = true; |
| 39 | + } |
42 | 40 | } |
43 | 41 | } |
44 | | - return count; |
| 42 | + return ans; |
45 | 43 | } |
46 | 44 | } |
0 commit comments