Skip to content

Commit 1fdda6c

Browse files
committed
DaleStudy#259 clone graph solution
1 parent 4242bd0 commit 1fdda6c

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

β€Žclone-graph/sungjinwi.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
"""
2+
풀이 :
3+
μž¬κ·€λ₯Ό μ΄μš©ν•΄μ„œ dfs풀이
4+
nodeλ₯Ό λ³΅μ œν•˜κ³  λ…Έλ“œμ˜ μ΄μ›ƒλœ λ…Έλ“œμ— λŒ€ν•΄μ„œ μž¬κ·€ν•¨μˆ˜ ν˜ΈμΆœμ„ 톡해 μ™„μ„±ν•œλ‹€
5+
6+
clones λ”•μ…”λ„ˆλ¦¬μ— 이미 λ³΅μ‚¬λœ node듀을 μ €μž₯ν•΄μ„œ 이미 볡제된 node에 λŒ€ν•΄
7+
ν•¨μˆ˜λ₯Ό ν˜ΈμΆœν•˜λ©΄ λ°”λ‘œ return
8+
9+
λ…Έλ“œμ˜ 수 : V(정점 : Vertex) μ΄μ›ƒμ˜ 수 : E(κ°„μ„  : Edge)라고 ν•  λ•Œ
10+
11+
TC : O(V + E)
12+
λ…Έλ“œμ™€ 이웃에 λŒ€ν•΄μ„œ μˆœνšŒν•˜λ―€λ‘œ
13+
14+
SC : O(V + E)
15+
ν•΄μ‹œν…Œμ΄λΈ”μ˜ 크기가 λ…Έλ“œμ˜ μˆ˜μ— λΉ„λ‘€ν•΄μ„œ 컀지고
16+
dfs의 ν˜ΈμΆœμŠ€νƒμ€ μ΄μ›ƒμ˜ 수만큼 μŒ“μ΄λ―€λ‘œ
17+
"""
18+
19+
"""
20+
# Definition for a Node.
21+
class Node:
22+
def __init__(self, val = 0, neighbors = None):
23+
self.val = val
24+
self.neighbors = neighbors if neighbors is not None else []
25+
"""
26+
from typing import Optional
27+
28+
class Solution:
29+
def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:
30+
if not node :
31+
return None
32+
33+
clones = {}
34+
35+
def dfs(node : Optional['Node']) -> Optional['Node']:
36+
if node in clones :
37+
return clones[node]
38+
clone = Node(node.val)
39+
clones[node] = clone
40+
for nei in node.neighbors :
41+
clone.neighbors.append(dfs(nei))
42+
return clone
43+
44+
return dfs(node)

0 commit comments

Comments
Β (0)