-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCloneGraph.java
More file actions
59 lines (52 loc) · 1.53 KB
/
CloneGraph.java
File metadata and controls
59 lines (52 loc) · 1.53 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
*
*/
package cc.dectinc.leetcode;
import cc.dectinc.api.structs.UndirectedGraphNode;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
/**
* @author chenshijiang
* @date Apr 12, 2015 4:56:52 PM
*
*/
public class CloneGraph {
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if (node == null) {
return null;
}
HashSet<Integer> doneNodes = new HashSet<Integer>();
HashMap<Integer, UndirectedGraphNode> nodeMap = new HashMap<Integer, UndirectedGraphNode>();
Queue<UndirectedGraphNode> nodes = new LinkedList<UndirectedGraphNode>();
nodes.add(node);
UndirectedGraphNode root = new UndirectedGraphNode(node.label);
Queue<UndirectedGraphNode> newNodes = new LinkedList<UndirectedGraphNode>();
newNodes.add(root);
nodeMap.put(root.label, root);
while (!nodes.isEmpty()) {
UndirectedGraphNode curNode = nodes.poll();
UndirectedGraphNode newNode = newNodes.poll();
if (doneNodes.contains(curNode.label)) {
continue;
}
for (UndirectedGraphNode nextNode : curNode.neighbors) {
UndirectedGraphNode newNextNode;
if (nodeMap.containsKey(nextNode.label)) {
newNextNode = nodeMap.get(nextNode.label);
} else {
newNextNode = new UndirectedGraphNode(nextNode.label);
nodeMap.put(newNextNode.label, newNextNode);
}
newNode.neighbors.add(newNextNode);
nodes.offer(nextNode);
newNodes.offer(newNextNode);
}
doneNodes.add(curNode.label);
}
return root;
}
public static void main(String[] args) {
}
}