forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchjung99.java
More file actions
49 lines (43 loc) · 1.18 KB
/
chjung99.java
File metadata and controls
49 lines (43 loc) · 1.18 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
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> neighbors;
public Node() {
val = 0;
neighbors = new ArrayList<Node>();
}
public Node(int _val) {
val = _val;
neighbors = new ArrayList<Node>();
}
public Node(int _val, ArrayList<Node> _neighbors) {
val = _val;
neighbors = _neighbors;
}
}
*/
class Solution {
public Node cloneGraph(Node node) {
if (node == null) return node;
return deepCopy(node);
}
public Node deepCopy(Node node) {
Deque<Node> deque = new ArrayDeque<>();
Node root = new Node(node.val, new ArrayList<>());
Map<Integer, Node> visit = new HashMap<>();
visit.put(1, root);
deque.add(node);
while (!deque.isEmpty()) {
Node cur = deque.poll();
for (Node next: cur.neighbors) {
if (!visit.containsKey(next.val)){
visit.put(next.val, new Node(next.val, new ArrayList<>()));
deque.add(next);
}
visit.get(cur.val).neighbors.add(visit.get(next.val));
}
}
return root;
}
}