-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQ133_CloneGraph.java
62 lines (57 loc) · 1.74 KB
/
Q133_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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import java.util.*;
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> neighbors;
public Node() {}
public Node(int _val,List<Node> _neighbors) {
val = _val;
neighbors = _neighbors;
}
};
*/
public class Q133_CloneGraph {
// // Method 1 3ms 96.38%
// public Node cloneGraph(Node node) {
// if (node == null) {
// return null;
// }
// Queue<Node> queue = new LinkedList<>();
// queue.add(node);
// Node clone = new Node(node.val, new ArrayList<>());
// Map<Node, Node> map = new HashMap<>();
// map.put(node, clone);
// while(!queue.isEmpty()) {
// Node cur = queue.poll();
// if (cur.neighbors != null) {
// for (Node neighbor : cur.neighbors) {
// if (!map.containsKey(neighbor)) {
// queue.add(neighbor);
// map.put(neighbor, new Node(neighbor.val, new ArrayList<>()));
// }
// map.get(cur).neighbors.add(map.get(neighbor));
// }
// }
// }
// return clone;
// }
// Method 2 3ms 96.38%
Map<Node, Node> map = new HashMap<>();
public Node cloneGraph(Node node) {
if (node == null) {
return null;
}
Node clone = new Node(node.val, new ArrayList<>());
map.put(node, clone);
for (Node neighbor : node.neighbors) {
if (!map.containsKey(neighbor)) {
Node cloneNeighbor = cloneGraph(neighbor);
clone.neighbors.add(cloneNeighbor);
} else {
clone.neighbors.add(map.get(neighbor));
}
}
return clone;
}
}