Skip to content

Commit c3e5de1

Browse files
committed
solve 3
1 parent 52cc3d5 commit c3e5de1

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

β€Žclone-graph/pmjuu.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
'''
2+
μ‹œκ°„ λ³΅μž‘λ„: O(V + E)
3+
- κ·Έλž˜ν”„μ˜ λͺ¨λ“  λ…Έλ“œλ₯Ό ν•œ λ²ˆμ”© λ°©λ¬Έν•΄μ•Ό ν•˜λ―€λ‘œ O(V)
4+
- 각 λ…Έλ“œμ˜ λͺ¨λ“  간선을 ν•œ λ²ˆμ”© 탐색해야 ν•˜λ―€λ‘œ O(E)
5+
- λ”°λΌμ„œ 전체 μ‹œκ°„ λ³΅μž‘λ„λŠ” O(V + E)
6+
7+
곡간 λ³΅μž‘λ„: O(V + E)
8+
- 클둠 λ…Έλ“œλ₯Ό μ €μž₯ν•˜λŠ” λ”•μ…”λ„ˆλ¦¬(clones): O(V)
9+
- BFS 탐색을 μœ„ν•œ 큐(queue): O(V)
10+
- 볡제된 κ·Έλž˜ν”„μ˜ λ…Έλ“œμ™€ κ°„μ„  μ €μž₯ 곡간: O(V + E)
11+
'''
12+
13+
from typing import Optional
14+
from collections import deque
15+
# Definition for a Node.
16+
class Node:
17+
def __init__(self, val = 0, neighbors = None):
18+
self.val = val
19+
self.neighbors = neighbors if neighbors is not None else []
20+
21+
class Solution:
22+
def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:
23+
if not node:
24+
return None
25+
26+
clones = { node.val: Node(node.val) }
27+
queue = deque([node])
28+
29+
while queue:
30+
current_node = queue.popleft()
31+
32+
for neighbor in current_node.neighbors:
33+
# add neighbors
34+
if neighbor.val not in clones.keys():
35+
queue.append(neighbor)
36+
clones[neighbor.val] = Node(neighbor.val)
37+
38+
clones[current_node.val].neighbors.append(clones[neighbor.val])
39+
40+
return clones[node.val]

0 commit comments

Comments
Β (0)