-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path133.clone-graph.java
More file actions
41 lines (40 loc) · 1.47 KB
/
133.clone-graph.java
File metadata and controls
41 lines (40 loc) · 1.47 KB
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
/**
* Definition for undirected graph.
* class UndirectedGraphNode {
* int label;
* List<UndirectedGraphNode> neighbors;
* UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
* };
*/
public class Solution {
public Map<Integer,UndirectedGraphNode> map;
public Set<UndirectedGraphNode> setBFS;
public Queue<UndirectedGraphNode> queueBFS;
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if (node==null) return null;
map = new HashMap<>();
//BFS Start
setBFS = new HashSet<>();
queueBFS = new ArrayDeque<>();
queueBFS.add(node);
while(!queueBFS.isEmpty()){
UndirectedGraphNode now = queueBFS.poll();
if (setBFS.contains(now)) continue;
else setBFS.add(now);
if (!map.containsKey(now.label)){
map.put(now.label,new UndirectedGraphNode(now.label));
}
for (UndirectedGraphNode neighbor:now.neighbors) {
if (!setBFS.contains(neighbor)){
queueBFS.add(neighbor);
}
if (!map.containsKey(neighbor.label)) {
map.put(neighbor.label, new UndirectedGraphNode(neighbor.label));
}
map.get(now.label).neighbors.add(map.get(neighbor.label));
}
}
//BFS End
return map.get(node.label);
}
}