-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCloneGraph.java
90 lines (82 loc) · 2.83 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
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* LeetCode
* 133. Clone Graph
* https://leetcode.com/problems/clone-graph/
* #Medium #Graph #BFS
*/
public class CloneGraph {
public static void main(String[] args) {
CloneGraph sol = new CloneGraph();
Node three = new Node(3);
Node node = new Node(1, Arrays.asList(new Node(2, Collections.singletonList(three)), new Node(4, Collections.singletonList(three))));
// Input: adjList = [[2,4],[1,3],[2,4],[1,3]]
// Output: [[2,4],[1,3],[2,4],[1,3]]
System.out.println("Original:\n" + node);
System.out.println("Cloned:\n" + sol.cloneGraph(node));
}
public Node cloneGraph(Node node) {
if (node == null) return null;
Deque<Node> deq = new ArrayDeque<>();
deq.add(node);
Map<Node, Node> bind = new HashMap<>();
Node newHead = new Node(node.val);
bind.put(node, newHead);
while (!deq.isEmpty()) {
Node current = deq.pollFirst();
Node cloned = bind.get(current);
for (Node neighbor : current.neighbors) {
if (!bind.containsKey(neighbor)) {
Node neighborClone = new Node(neighbor.val);
bind.put(neighbor, neighborClone);
deq.add(neighbor);
}
cloned.neighbors.add(bind.get(neighbor));
}
}
return newHead;
}
private static class Node {
public int val;
public List<Node> neighbors;
public Node(int val) {
this.val = val;
neighbors = new ArrayList<>();
}
public Node(int val, List<Node> neighbors) {
this.val = val;
this.neighbors = neighbors;
}
@Override
public String toString() {
Deque<Node> deq = new ArrayDeque<>();
deq.add(this);
Set<Node> visited = new HashSet<>();
StringBuilder sb = new StringBuilder();
while (!deq.isEmpty()) {
int size = deq.size();
for (int i = 0; i < size; i++) {
Node nd = deq.pollFirst();
if (nd == null) continue;
sb.append(nd.val).append('(').append(nd.hashCode()).append(')').append(',');
for (Node neighbor : nd.neighbors) {
if (visited.contains(neighbor)) continue;
deq.add(neighbor);
visited.add(neighbor);
}
}
sb.append("->");
}
return sb.toString();
}
}
}