forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCloneGraph.java
32 lines (27 loc) · 1.07 KB
/
CloneGraph.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
package medium;
import classes.UndirectedGraphNode;
import java.util.*;
/**
* Created by fishercoder1534 on 9/30/16.
*/
public class CloneGraph {
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if(node == null) return node;
Map<Integer, UndirectedGraphNode> map = new HashMap();
Queue<UndirectedGraphNode> queue = new LinkedList();
UndirectedGraphNode root = new UndirectedGraphNode(node.label);
map.put(root.label, root);
queue.offer(node);//remember to offer the original input node into the queue which contains all the information
while(!queue.isEmpty()){
UndirectedGraphNode curr = queue.poll();
for(UndirectedGraphNode eachNode : curr.neighbors){
if(!map.containsKey(eachNode.label)){
map.put(eachNode.label, new UndirectedGraphNode(eachNode.label));
queue.offer(eachNode);
}
map.get(curr.label).neighbors.add(map.get(eachNode.label));
}
}
return root;
}
}