-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCloneGraph.java
39 lines (31 loc) · 1.04 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
33
34
35
36
37
38
39
package com.smlnskgmail.jaman.leetcodejava.medium;
import com.smlnskgmail.jaman.leetcodejava.support.NodeWithNeighbors;
import java.util.HashMap;
import java.util.Map;
// https://www.youtube.com/watch?v=y5u74DCEnBc/
public class CloneGraph {
private final NodeWithNeighbors input;
public CloneGraph(NodeWithNeighbors input) {
this.input = input;
}
public NodeWithNeighbors solution() {
return cloneGraph(input, new HashMap<>());
}
private NodeWithNeighbors cloneGraph(
NodeWithNeighbors node,
Map<NodeWithNeighbors, NodeWithNeighbors> values
) {
if (node != null) {
if (values.containsKey(node)) {
return values.get(node);
}
NodeWithNeighbors root = new NodeWithNeighbors(node.val);
values.put(node, root);
for (NodeWithNeighbors neighbor : node.neighbors) {
root.neighbors.add(cloneGraph(neighbor, values));
}
return root;
}
return null;
}
}