-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathSolution.java
More file actions
29 lines (24 loc) · 849 Bytes
/
Solution.java
File metadata and controls
29 lines (24 loc) · 849 Bytes
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
import java.util.*;
public class Solution {
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
return cloneGraph(node, new HashMap<UndirectedGraphNode, UndirectedGraphNode>());
}
UndirectedGraphNode cloneGraph(UndirectedGraphNode node, Map<UndirectedGraphNode, UndirectedGraphNode> map) {
if (node == null) return null;
UndirectedGraphNode newNode = map.get(node);
if (newNode != null) return newNode;
newNode = new UndirectedGraphNode(node.label);
map.put(node, newNode);
for (UndirectedGraphNode neighbor: node.neighbors) {
newNode.neighbors.add(cloneGraph(neighbor, map));
}
return newNode;
}
}
class UndirectedGraphNode {
int label;
ArrayList<UndirectedGraphNode> neighbors = new ArrayList<UndirectedGraphNode>();
UndirectedGraphNode(int x) {
this.label = x;
}
}