forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKwonNayeon.py
More file actions
69 lines (56 loc) ยท 2.4 KB
/
KwonNayeon.py
File metadata and controls
69 lines (56 loc) ยท 2.4 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
"""
Constraints:
- The number of nodes in the graph is in the range [0, 100].
- 1 <= Node.val <= 100
- Node.val is unique for each node.
- There are no repeated edges and no self-loops in the graph.
- The Graph is connected and all nodes can be visited starting from the given node.
Shallow Copy (์์ ๋ณต์ฌ):
- ๋
ธ๋ ์์ฒด๋ ์๋ก์ด ๋ฉ๋ชจ๋ฆฌ์ ๋ณต์ฌ
- ํ์ง๋ง neighbors๋ ์๋ณธ ๋
ธ๋์ neighbors๋ฅผ ๊ทธ๋๋ก ์ฐธ์กฐ
์์) ์๋ณธ Node1์ด Node2๋ฅผ neighbor๋ก ๊ฐ์ง ๋
๋ณต์ฌํ CopyNode1์ ์๋ก์ด ๋
ธ๋์ง๋ง
CopyNode1์ neighbor๋ ์๋ณธ์ Node2๋ฅผ ๊ทธ๋๋ก ๊ฐ๋ฆฌํด
Deep Copy (๊น์ ๋ณต์ฌ):
- ๋
ธ๋๋ ์๋ก์ด ๋ฉ๋ชจ๋ฆฌ์ ๋ณต์ฌ
- neighbors๋ ๋ชจ๋ ์๋ก์ด ๋
ธ๋๋ก ๋ณต์ฌํด์ ์ฐ๊ฒฐ
์์) ์๋ณธ Node1์ด Node2๋ฅผ neighbor๋ก ๊ฐ์ง ๋
CopyNode1๋ ์๋ก์ด ๋
ธ๋์ด๊ณ
CopyNode1์ neighbor๋ ์๋ก ๋ง๋ CopyNode2๋ฅผ ๊ฐ๋ฆฌํด
Time Complexity: O(N + E)
- N: ๋
ธ๋์ ๊ฐ์
- E: ์ฃ์ง์ ๊ฐ์
- ๋ชจ๋ ๋
ธ๋์ ์ฃ์ง๋ฅผ ํ ๋ฒ์ฉ ๋ฐฉ๋ฌธ
Space Complexity: O(N)
- N: ๋
ธ๋์ ๊ฐ์
- dictionary์ ์ฌ๊ท ํธ์ถ ์คํ ๊ณต๊ฐ
ํ์ด ๋ฐฉ๋ฒ:
- ๋ฌธ์ ์์ ์๊ตฌํ๋ ๊ฒ: Deep copy
- Base case: ๋น ๊ทธ๋ํ ์ฒ๋ฆฌ
- ๋์
๋๋ฆฌ ์์ฑ ํ dfs
- ๋ง์ฝ ์ด๋ฏธ ๋ณต์ฌํ ๋
ธ๋๋ผ๋ฉด ํด๋น ๋ณต์ฌ๋ณธ์ ๋ฐํํจ
- ์๋๋ผ๋ฉด, ์๋ก์ด ๋
ธ๋๋ฅผ ์์ฑํ์ฌ ๋์
๋๋ฆฌ์ ์ ์ฅ
- ์ด์ ๋
ธ๋์ ๊ฒฝ์ฐ์๋ dfs()๋ก ๋ณต์ฌ๋ณธ์ ๋ง๋ค์ด์ ํ์ฌ ๋
ธ๋์ neighbors ๋ฆฌ์คํธ์ ์ถ๊ฐํจ
- ์ฃผ์ด์ง ๋
ธ๋๋ถํฐ ์ฌ๊ท ์์
# Definition for a Node.
class Node:
def __init__(self, val = 0, neighbors = None):
self.val = val
self.neighbors = neighbors if neighbors is not None else []
"""
class Solution:
def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:
# ๋น ๊ทธ๋ํ ์ฒ๋ฆฌ
if not node:
return None
dict = {}
def dfs(node):
if node.val in dict: # ์ด๋ฏธ ๋ณต์ฌํ ๋
ธ๋๋ผ๋ฉด
return dict[node.val] # ํด๋น ๋ณต์ฌ๋ณธ ๋ฐํ
# ์๋ก์ด ๋
ธ๋ ์์ฑ
copy = Node(node.val)
dict[node.val] = copy
for neighbor in node.neighbors: # ์๋ณธ์ ๊ฐ ์ด์์ ๋ํ์ฌ
copy.neighbors.append(dfs(neighbor)) # ๊ทธ ์ด์์ ๋ณต์ฌ๋ณธ์ ๋ง๋ค์ด์ ์ถ๊ฐํจ
return copy
return dfs(node)