forked from ex01tus/leetcode-grind
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCloneGraph.java
More file actions
70 lines (54 loc) · 1.67 KB
/
CloneGraph.java
File metadata and controls
70 lines (54 loc) · 1.67 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
60
61
62
63
64
65
66
67
68
69
70
package graph;
import java.util.*;
/**
* Description: https://leetcode.com/problems/clone-graph
* Difficulty: Medium
* Time complexity: O(n)
* Space complexity: O(n)
*/
public class CloneGraph {
private Map<Integer, Integer> visited;
private Map<Integer, Node> newNodes;
public Node cloneGraph(Node node) {
if (node == null) return null;
visited = new HashMap<>();
newNodes = new HashMap<>();
dfs(node);
return newNodes.get(1);
}
private void dfs(Node start) {
Deque<Node> stack = new LinkedList<>();
stack.push(start);
while (!stack.isEmpty()) {
Node current = stack.pop();
if (visited.get(current.val) == null) {
Node currentCopy = clone(current);
visited.put(current.val, 1);
stack.push(current);
for (Node neighbor : current.neighbors) {
Node neighborCopy = clone(neighbor);
currentCopy.neighbors.add(neighborCopy);
if (visited.get(neighbor.val) == null) {
stack.push(neighbor);
}
}
}
}
}
private Node clone(Node current) {
Node copyNode = newNodes.get(current.val);
if (copyNode == null) {
copyNode = new Node(current.val);
newNodes.put(current.val, copyNode);
}
return copyNode;
}
private static class Node {
public int val;
public List<Node> neighbors;
public Node(int val) {
this.val = val;
this.neighbors = new ArrayList<>();
}
}
}