forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathforest000014.java
More file actions
77 lines (63 loc) ยท 3.05 KB
/
forest000014.java
File metadata and controls
77 lines (63 loc) ยท 3.05 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
/*
# Time Complexity: O(n * e), where e is the maximum number of edges of a node
- ์ ์ฒด node๋ฅผ ์ํํ๋ฉด์, ๊ทธ ์ด์์ ํด๋นํ๋ ๋ณต์ ๋ณธ์ ์์ฑํด์ ๋ณต์ ๋ณธ๋ผ๋ฆฌ ์ฐ๊ฒฐํด์ค๋ค.
- ๋จ, ์ค๋ณต ๋ฐฉ๋ฌธ์ ๋ง๊ธฐ ์ํด, ๋ณต์ ๋ณธ์ด ์ด๋ฏธ ์ด์ ๋ณต์ ๋ณธ์ ๊ฐ์ง๊ณ ์๋์ง ํ์ธํ๋ค. ์ด ๊ณผ์ ์์ O(e)๋งํผ์ List ์ํ๋ฅผ ํ๋ค.
# Space Complexity: O(n)
- ์ ์ฒด Node ๋งํผ์ ๋ฉ๋ชจ๋ฆฌ๊ฐ ํ์ํ๋ค.
(Space Complexity๋ฅผ ๊ณ์ฐํ๊ธฐ ์ ๋งคํ ์ธก๋ฉด์ด ์๋ค์. ์ ๋ ์ง๊ธ๊น์ง ์ถ๋ ฅ์ space complexity์ ํฌํจํ์ง ์๊ณ ๊ณ์ฐํ์๋๋ฐ, ๊ทธ ์ด์ ๋ "์ด๋ค ์๊ณ ๋ฆฌ์ฆ์ ๊ตฌํํ๋ ์ถ๋ ฅ์ ๋์ผํ๊ธฐ ๋๋ฌธ"์ธ๋ฐ์. ์ด ๋ฌธ์ ์ ๊ฒฝ์ฐ์ ์ถ๋ ฅ์ Node ํ๋์ด์ง๋ง, ์ค์ ๋ก๋ Node ์ ์ฒด๋งํผ์ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ๋ฐ๋์ ์์ฑํด์ผ ํ๋ค๋ ํน์์ฑ์ด ์์ต๋๋ค. ๊ทธ๋์ "์ด๋ป๊ฒ ๊ตฌํํ๋ ๋์ผํ๊ฒ ์ฌ์ฉํด์ผ๋ง ํ๋ ๋ฉ๋ชจ๋ฆฌ๋ Space Complexity์์ ๋ฐฐ์ ํ๋ค" ๋ผ๋ ๋
ผ๋ฆฌ๋ก๋ง ๋ณด์๋ฉด O(1)์ผ ๊ฒ ๊ฐ๊ณ , "์ถ๋ ฅ์ ์ ์ธํ ๋ฉ๋ชจ๋ฆฌ ์ฌ์ฉ์ Space Complexity์ ํฌํจํ๋ค" ๋ผ๋ ๋
ผ๋ฆฌ๋๋ก๋ผ๋ฉด O(n)์ธ ๊ฒ ๊ฐ์ต๋๋ค.)
์ ์ฒด ๋
ธ๋๋ฅผ DFS๋ก ์ํํ๋ฉด์ ์ด์ ๋
ธ๋์ ๋ณต์ ๋ณธ์ ์์ฑํ์ฌ ํ์ฌ ๋
ธ๋์ ๋ณต์ ๋ณธ๊ณผ ์ฐ๊ฒฐ์ ๋งบ์ด์ค๋๋ค.
๋ค๋ง, ์ค๋ณต ๋ฐฉ๋ฌธ์ ๋ง๊ธฐ ์ํด, ๋ณต์ ๋ณธ์ด ์ด๋ฏธ ์ด์ ๋ณต์ ๋ณธ์ ๊ฐ์ง๊ณ ์๋์ง ํ์ธํ๋ค.
๋ํ ์ํ ์ฐธ์กฐ(cycle ๊ตฌ์กฐ)๋ฅผ ๋ง๊ธฐ ์ํด์, ๋ณต์ ๋ณธ ๋
ธ๋๋ฅผ ์์ฑ์ ๋จ์ํ new ํค์๋๋ฅผ ์ฌ์ฉํ์ง ์๊ณ , ๋ณ๋์ map์ ํตํด ์ฑ๊ธํค์ผ๋ก ์์ฑํ๋ค. (๊ฐ ๋
ธ๋์ val์ distinctํ๋ค๋ ์ ์ ์ด์ฉ)
// 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 {
Map<Integer, Node> map = new HashMap<>();
public Node cloneGraph(Node node) {
if (node == null) {
return null;
}
Node newNode = createNode(node.val);
dfs(node);
return newNode;
}
public Node createNode(int val) {
if (!map.containsKey(val)) {
map.put(val, new Node(val));
}
return map.get(val);
}
public void dfs(Node oldNode) {
Node newNode = map.get(oldNode.val);
for (Node oldNeighbor : oldNode.neighbors) {
boolean hasIt = false;
for (Node newNeighbor : newNode.neighbors) {
if (newNeighbor.val == oldNeighbor.val) {
hasIt = true;
break;
}
}
if (!hasIt) {
Node newNeighbor = createNode(oldNeighbor.val);
newNode.neighbors.add(newNeighbor);
newNeighbor.neighbors.add(newNode);
dfs(oldNeighbor);
}
}
}
}