|
6 | 6 | import java.util.Queue;
|
7 | 7 |
|
8 | 8 | /**
|
| 9 | + * 323. Number of Connected Components in an Undirected Graph |
| 10 | + * |
9 | 11 | * Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph.
|
10 | 12 |
|
11 | 13 | Example 1:
|
|
28 | 30 | You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.
|
29 | 31 | */
|
30 | 32 | public class _323 {
|
| 33 | + public static class Solution1 { |
31 | 34 |
|
32 |
| - public int countComponents(int n, int[][] edges) { |
33 |
| - if (n <= 1) { |
34 |
| - return n; |
35 |
| - } |
| 35 | + public int countComponents(int n, int[][] edges) { |
| 36 | + if (n <= 1) { |
| 37 | + return n; |
| 38 | + } |
36 | 39 |
|
37 |
| - List<List<Integer>> adList = new ArrayList<List<Integer>>(); |
38 |
| - for (int i = 0; i < n; i++) { |
39 |
| - adList.add(new ArrayList<Integer>()); |
40 |
| - } |
| 40 | + List<List<Integer>> adList = new ArrayList<>(); |
| 41 | + for (int i = 0; i < n; i++) { |
| 42 | + adList.add(new ArrayList<>()); |
| 43 | + } |
41 | 44 |
|
42 |
| - for (int[] edge : edges) { |
43 |
| - adList.get(edge[0]).add(edge[1]); |
44 |
| - adList.get(edge[1]).add(edge[0]); |
45 |
| - } |
| 45 | + for (int[] edge : edges) { |
| 46 | + adList.get(edge[0]).add(edge[1]); |
| 47 | + adList.get(edge[1]).add(edge[0]); |
| 48 | + } |
46 | 49 |
|
47 |
| - for (List<Integer> list : adList) { |
48 |
| - for (int i : list) { |
49 |
| - System.out.print(i + ", "); |
| 50 | + for (List<Integer> list : adList) { |
| 51 | + for (int i : list) { |
| 52 | + System.out.print(i + ", "); |
| 53 | + } |
| 54 | + System.out.println(); |
50 | 55 | }
|
51 |
| - System.out.println(); |
52 |
| - } |
53 | 56 |
|
54 |
| - boolean[] visited = new boolean[n]; |
55 |
| - int count = 0; |
56 |
| - for (int i = 0; i < n; i++) { |
57 |
| - if (!visited[i]) { |
58 |
| - count++; |
59 |
| - Queue<Integer> q = new LinkedList<Integer>(); |
60 |
| - q.offer(i); |
61 |
| - while (!q.isEmpty()) { |
62 |
| - int index = q.poll(); |
63 |
| - visited[index] = true; |
64 |
| - for (int j : adList.get(index)) { |
65 |
| - if (!visited[j]) { |
66 |
| - q.offer(j); |
| 57 | + boolean[] visited = new boolean[n]; |
| 58 | + int count = 0; |
| 59 | + for (int i = 0; i < n; i++) { |
| 60 | + if (!visited[i]) { |
| 61 | + count++; |
| 62 | + Queue<Integer> q = new LinkedList<>(); |
| 63 | + q.offer(i); |
| 64 | + while (!q.isEmpty()) { |
| 65 | + int index = q.poll(); |
| 66 | + visited[index] = true; |
| 67 | + for (int j : adList.get(index)) { |
| 68 | + if (!visited[j]) { |
| 69 | + q.offer(j); |
| 70 | + } |
67 | 71 | }
|
68 | 72 | }
|
69 | 73 | }
|
70 | 74 | }
|
71 |
| - } |
72 | 75 |
|
73 |
| - return count; |
| 76 | + return count; |
| 77 | + } |
74 | 78 | }
|
75 | 79 |
|
76 | 80 | }
|
0 commit comments