|
7 | 7 |
|
8 | 8 | public class _323 { |
9 | 9 | public static class Solution1 { |
10 | | - |
| 10 | + /** |
| 11 | + * Use BFS to iterate through all nodes and their connected neighbors |
| 12 | + */ |
11 | 13 | public int countComponents(int n, int[][] edges) { |
12 | | - if (n <= 1) { |
13 | | - return n; |
14 | | - } |
15 | | - |
16 | | - List<List<Integer>> adList = new ArrayList<>(); |
| 14 | + //build the adjacency list; |
| 15 | + List<List<Integer>> adj = new ArrayList<>(); |
17 | 16 | for (int i = 0; i < n; i++) { |
18 | | - adList.add(new ArrayList<>()); |
| 17 | + adj.add(new ArrayList<>()); |
19 | 18 | } |
20 | | - |
21 | 19 | for (int[] edge : edges) { |
22 | | - adList.get(edge[0]).add(edge[1]); |
23 | | - adList.get(edge[1]).add(edge[0]); |
24 | | - } |
25 | | - |
26 | | - for (List<Integer> list : adList) { |
27 | | - for (int i : list) { |
28 | | - System.out.print(i + ", "); |
29 | | - } |
30 | | - System.out.println(); |
| 20 | + adj.get(edge[0]).add(edge[1]); |
| 21 | + adj.get(edge[1]).add(edge[0]); |
31 | 22 | } |
32 | 23 |
|
33 | 24 | boolean[] visited = new boolean[n]; |
34 | 25 | int count = 0; |
| 26 | + |
35 | 27 | for (int i = 0; i < n; i++) { |
36 | 28 | if (!visited[i]) { |
37 | 29 | count++; |
38 | | - Queue<Integer> q = new LinkedList<>(); |
39 | | - q.offer(i); |
40 | | - while (!q.isEmpty()) { |
41 | | - int index = q.poll(); |
42 | | - visited[index] = true; |
43 | | - for (int j : adList.get(index)) { |
44 | | - if (!visited[j]) { |
45 | | - q.offer(j); |
| 30 | + Queue<Integer> queue = new LinkedList<>(); |
| 31 | + queue.offer(i); |
| 32 | + |
| 33 | + while (!queue.isEmpty()) { |
| 34 | + int currNode = queue.poll(); |
| 35 | + visited[currNode] = true; |
| 36 | + for (int neighbor : adj.get(currNode)) { |
| 37 | + if (!visited[neighbor]) { |
| 38 | + queue.offer(neighbor); |
46 | 39 | } |
47 | 40 | } |
48 | 41 | } |
|
0 commit comments