forked from super30admin/BFS-3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCloneGraph.java
65 lines (44 loc) · 1.26 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
/*
Space complexity : O(V) Number of nodes
Time complexity : O(V+E)visiting every node and every edges
Clone graph : is worked on leetcode : YES
*/
/*
// 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> visited = new HashMap();
public Node cloneGraph(Node node) {
if(node == null) return node;
Node newNode = deepCopy(node);
return newNode;
}
private Node deepCopy(Node node) {
if(visited.containsKey(node.val)){
return visited.get(node.val);
}else{
Node n = new Node(node.val, new ArrayList<Node>());
visited.putIfAbsent(n.val, n);
for(Node _node : node.neighbors){
n.neighbors.add(deepCopy(_node));
}
return n;
}
}
}