-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
39 lines (30 loc) · 973 Bytes
/
Solution.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 org.example.problems.clone_graph;
import org.example.helpers.graph.Node;
import org.example.problems.SolutionInterface;
import java.util.HashMap;
import java.util.Map;
public class Solution implements SolutionInterface {
@Override
public String getName() {
return "Clone Graph";
}
@Override
public String getUrl() {
return "https://leetcode.com/problems/clone-graph/";
}
public Node cloneGraph(Node node) {
if (node == null) return null;
return getClone(new HashMap<>(), node);
}
private Node getClone(Map<Node, Node> clonesMap, Node original) {
if (clonesMap.containsKey(original)) {
return clonesMap.get(original);
}
Node clone = new Node(original.val);
clonesMap.put(original, clone);
for (Node neighbour: original.neighbors) {
clone.neighbors.add(getClone(clonesMap, neighbour));
}
return clone;
}
}