forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTessa1217.java
More file actions
59 lines (50 loc) ยท 1.35 KB
/
Tessa1217.java
File metadata and controls
59 lines (50 loc) ยท 1.35 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
/*
// 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;
}
}
*/
import java.util.HashMap;
import java.util.Map;
/**
* ์ฐธ์กฐ ๋
ธ๋๋ ๋ฌด๋ฐฉํฅ ๊ทธ๋ํ์ ์ฐ๊ฒฐ๋์ด์๋ค. ๊ทธ๋ํ์ deep copy(clone)์ ๋ฐํํ์ธ์.
*/
class Solution {
// ๋ฐฉ๋ฌธํ ๋
ธ๋๋ฅผ ๊ธฐ์ตํ Map ์ ์ธ
Map<Node, Node> visited = new HashMap<>();
public Node cloneGraph(Node node) {
return clone(node);
}
public Node clone(Node node) {
if (node == null) {
return null;
}
// ์ด๋ฏธ ๋ฐฉ๋ฌธํ์ผ๋ฉด Map์์ ๊บผ๋ด์ ๋ฐํ
if (visited.containsKey(node)) {
return visited.get(node);
}
// ์ ๊ท Node ์์ฑ
Node newNode = new Node(node.val);
visited.put(node, newNode);
// ์ธ์ ๋
ธ๋ Clone
if (node.neighbors != null && !node.neighbors.isEmpty()) {
for (Node neighbor : node.neighbors) {
newNode.neighbors.add(clone(neighbor));
}
}
return newNode;
}
}