forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_323.java
56 lines (47 loc) · 1.52 KB
/
_323.java
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class _323 {
public static class Solution1 {
public int countComponents(int n, int[][] edges) {
if (n <= 1) {
return n;
}
List<List<Integer>> adList = new ArrayList<>();
for (int i = 0; i < n; i++) {
adList.add(new ArrayList<>());
}
for (int[] edge : edges) {
adList.get(edge[0]).add(edge[1]);
adList.get(edge[1]).add(edge[0]);
}
for (List<Integer> list : adList) {
for (int i : list) {
System.out.print(i + ", ");
}
System.out.println();
}
boolean[] visited = new boolean[n];
int count = 0;
for (int i = 0; i < n; i++) {
if (!visited[i]) {
count++;
Queue<Integer> q = new LinkedList<>();
q.offer(i);
while (!q.isEmpty()) {
int index = q.poll();
visited[index] = true;
for (int j : adList.get(index)) {
if (!visited[j]) {
q.offer(j);
}
}
}
}
}
return count;
}
}
}