forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGeegong.java
More file actions
84 lines (71 loc) Β· 2.33 KB
/
Geegong.java
File metadata and controls
84 lines (71 loc) Β· 2.33 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
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
import java.util.*;
/*
// 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;
}
}
*/
public class Geegong {
/**
* dfs λ°©μμΌλ‘ νμ΄
* visited λ‘ memoization νμ¬ λ°©λ¬Έν΄μ 볡μ¬κ° λ λ
Έλλ€μ μ μ₯
* νλ² λ°©λ¬Ένλ λ
Έλλ₯Ό neighbors νμμ ν΅ν΄ λ λ°©λ¬Ένκ² λλ©΄ visited μμ κΊΌλ΄μ return νλλ‘ νλ€.
*
* time complexity : O(2N) -> O(N)
* space complexity : O(N)
* @param node
* @return
*/
public Node cloneGraph(Node node) {
// nodeμ μ§μ
ν μκ°μ λ°λ‘ visited μ λ£μ΄μ cloned λ node λ€μ μ§μ΄λ£λλ‘ κ΄λ¦¬
Map<Integer, Node> visited = new HashMap<>();
if (node == null) {
return null;
}
Node result = cloneDeeply(node, visited);
return result;
}
public Node cloneDeeply(Node origin, Map<Integer, Node> visited) {
// visited μλ cloned λ node λ€μ μ μ₯νκ³ μμ΄ νλ² λ°©λ¬Ένλ λ
ΈλλΌλ©΄ 볡μ¬ν λ
Έλλ₯Ό 리ν΄νλ€.
if (visited.containsKey(origin.val)) {
return visited.get(origin.val);
}
Node clonedTarget = new Node(origin.val);
visited.put(origin.val, clonedTarget);
for (Node neighbor : origin.neighbors) {
Node clonedNeighbor = cloneDeeply(neighbor, visited);
clonedTarget.neighbors.add(clonedNeighbor);
}
return clonedTarget;
}
// μ΄λ―Έ λ€λ₯Έ λΆλ€μ΄ Node ν΄λμ€λ₯Ό λ§μ΄ λ§λ€μ΄λμΌμ
μ.. κ°μΈ ν΄λμ€ μμ μ΄λ ν΄λμ€λ‘ Node λ§λ¬
public static 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;
}
}
}