find the connected component in the undirected graph


Find the Connected Component in the Undirected Graph

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
public List<List<Integer>> connectedSet(ArrayList<UndirectedGraphNode> nodes) {

List<List<Integer>> ans = new ArrayList<List<Integer>>();
if (nodes == null || nodes.size() == 0)
return ans;
HashSet<UndirectedGraphNode> set = new HashSet<>();
for (UndirectedGraphNode node : nodes) {
if (set.contains(node))
continue;
Queue<UndirectedGraphNode> q = new LinkedList<>();
List<Integer> temp = new ArrayList<>();
q.offer(node);
while (!q.isEmpty()) {
UndirectedGraphNode cur = q.poll();
if (set.contains(cur))
continue;
temp.add(cur.label);
set.add(cur);
for (UndirectedGraphNode neighbor : cur.neighbors) {
q.offer(neighbor);
}
}
// I don't understand why the OJ ask this
Collections.sort(temp);
ans.add(new ArrayList<Integer>(temp));
}
return ans;
}