-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCloneGraph.java
More file actions
31 lines (31 loc) · 1.06 KB
/
CloneGraph.java
File metadata and controls
31 lines (31 loc) · 1.06 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
/**
* Definition for undirected graph.
* class UndirectedGraphNode {
* int label;
* List<UndirectedGraphNode> neighbors;
* UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
* };
*/
public class Solution {
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if (node == null) {
return null;
}
Queue<UndirectedGraphNode> q = new LinkedList<>();
q.offer(node);
UndirectedGraphNode clone = new UndirectedGraphNode(node.label);
Map<Integer, UndirectedGraphNode> map = new HashMap<>();
map.put(clone.label, clone);
while (!q.isEmpty()) {
UndirectedGraphNode cur = q.poll();
for (UndirectedGraphNode ne: cur.neighbors) {
if (!map.containsKey(ne.label)){
map.put(ne.label, new UndirectedGraphNode(ne.label));
q.offer(ne);
}
map.get(cur.label).neighbors.add(map.get(ne.label));
}
}
return clone;
}
}