-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClone Graph.java
More file actions
55 lines (51 loc) · 1.32 KB
/
Clone Graph.java
File metadata and controls
55 lines (51 loc) · 1.32 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
/*
// 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 {
HashMap<Integer, Node> map = new HashMap<>();
HashSet<Node> visited = new HashSet<>();
public Node cloneGraph(Node node) {
if(node == null)return null;
clone(node);
cloneG(node);
return map.get(node.val);
}
public void clone(Node node) {
if (!map.containsKey(node.val)) {
Node block = new Node(node.val);
map.put(node.val, block);
// visited.add(node);
for (Node val : node.neighbors) {
clone(val);
}
}
}
public void cloneG(Node node) {
if (!visited.contains(node)) {
visited.add(node);
Node curr = map.get(node.val);
for (Node value : node.neighbors) {
curr.neighbors.add(map.get(value.val));
}
for (Node value : node.neighbors) {
cloneG(value);
}
}
}
}