Skip to content

Commit bb38232

Browse files
committed
solve: Clone Graph
1 parent 1d0a53f commit bb38232

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

โ€Žclone-graph/KwonNayeon.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
"""
2+
Constraints:
3+
- The number of nodes in the graph is in the range [0, 100].
4+
- 1 <= Node.val <= 100
5+
- Node.val is unique for each node.
6+
- There are no repeated edges and no self-loops in the graph.
7+
- The Graph is connected and all nodes can be visited starting from the given node.
8+
9+
Shallow Copy (์–•์€ ๋ณต์‚ฌ):
10+
- ๋…ธ๋“œ ์ž์ฒด๋Š” ์ƒˆ๋กœ์šด ๋ฉ”๋ชจ๋ฆฌ์— ๋ณต์‚ฌ
11+
- ํ•˜์ง€๋งŒ neighbors๋Š” ์›๋ณธ ๋…ธ๋“œ์˜ neighbors๋ฅผ ๊ทธ๋Œ€๋กœ ์ฐธ์กฐ
12+
์˜ˆ์‹œ) ์›๋ณธ Node1์ด Node2๋ฅผ neighbor๋กœ ๊ฐ€์งˆ ๋•Œ
13+
๋ณต์‚ฌํ•œ CopyNode1์€ ์ƒˆ๋กœ์šด ๋…ธ๋“œ์ง€๋งŒ
14+
CopyNode1์˜ neighbor๋Š” ์›๋ณธ์˜ Node2๋ฅผ ๊ทธ๋Œ€๋กœ ๊ฐ€๋ฆฌํ‚ด
15+
16+
Deep Copy (๊นŠ์€ ๋ณต์‚ฌ):
17+
- ๋…ธ๋“œ๋Š” ์ƒˆ๋กœ์šด ๋ฉ”๋ชจ๋ฆฌ์— ๋ณต์‚ฌ
18+
- neighbors๋„ ๋ชจ๋‘ ์ƒˆ๋กœ์šด ๋…ธ๋“œ๋กœ ๋ณต์‚ฌํ•ด์„œ ์—ฐ๊ฒฐ
19+
์˜ˆ์‹œ) ์›๋ณธ Node1์ด Node2๋ฅผ neighbor๋กœ ๊ฐ€์งˆ ๋•Œ
20+
CopyNode1๋„ ์ƒˆ๋กœ์šด ๋…ธ๋“œ์ด๊ณ 
21+
CopyNode1์˜ neighbor๋„ ์ƒˆ๋กœ ๋งŒ๋“  CopyNode2๋ฅผ ๊ฐ€๋ฆฌํ‚ด
22+
23+
Time Complexity: O(N + E)
24+
- N: ๋…ธ๋“œ์˜ ๊ฐœ์ˆ˜
25+
- E: ์—ฃ์ง€์˜ ๊ฐœ์ˆ˜
26+
- ๋ชจ๋“  ๋…ธ๋“œ์™€ ์—ฃ์ง€๋ฅผ ํ•œ ๋ฒˆ์”ฉ ๋ฐฉ๋ฌธ
27+
28+
Space Complexity: O(N)
29+
- N: ๋…ธ๋“œ์˜ ๊ฐœ์ˆ˜
30+
- dictionary์™€ ์žฌ๊ท€ ํ˜ธ์ถœ ์Šคํƒ ๊ณต๊ฐ„
31+
32+
# Definition for a Node.
33+
class Node:
34+
def __init__(self, val = 0, neighbors = None):
35+
self.val = val
36+
self.neighbors = neighbors if neighbors is not None else []
37+
38+
์ฐธ๊ณ  ์‚ฌํ•ญ:
39+
- ํ˜ผ์ž ํ’€๊ธฐ ์–ด๋ ค์›Œ์„œ, ๋ฌธ์ œ์™€ ๋‹ต์„ ์ดํ•ดํ•˜๋Š” ๊ฒƒ์— ์ง‘์ค‘ํ–ˆ์Šต๋‹ˆ๋‹ค!
40+
"""
41+
class Solution:
42+
def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:
43+
if not node:
44+
return None
45+
46+
dict = {}
47+
48+
def dfs(node):
49+
if node.val in dict: # ์ด๋ฏธ ๋ณต์‚ฌํ•œ ๋…ธ๋“œ๋ผ๋ฉด
50+
return dict[node.val] # ํ•ด๋‹น ๋ณต์‚ฌ๋ณธ ๋ฐ˜ํ™˜
51+
52+
# ์ƒˆ๋กœ์šด ๋…ธ๋“œ ์ƒ์„ฑ
53+
copy = Node(node.val)
54+
dict[node.val] = copy # dictionary์— ๊ธฐ๋ก
55+
56+
# ๊ฐ neighbor์— ๋Œ€ํ•ด์„œ๋„ ๊ฐ™์€ ๊ณผ์ • ์ˆ˜ํ–‰
57+
for neighbor in node.neighbors:
58+
copy.neighbors.append(dfs(neighbor))
59+
60+
return copy
61+
62+
return dfs(node)
63+

0 commit comments

Comments
ย (0)