forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsungjinwi.py
44 lines (35 loc) Β· 1.33 KB
/
sungjinwi.py
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
"""
νμ΄ :
μ¬κ·λ₯Ό μ΄μ©ν΄μ dfsνμ΄
nodeλ₯Ό 볡μ νκ³ λ
Έλμ μ΄μλ λ
Έλμ λν΄μ μ¬κ·ν¨μ νΈμΆμ ν΅ν΄ μμ±νλ€
clones λμ
λ리μ μ΄λ―Έ 볡μ¬λ nodeλ€μ μ μ₯ν΄μ μ΄λ―Έ 볡μ λ nodeμ λν΄
ν¨μλ₯Ό νΈμΆνλ©΄ λ°λ‘ return
λ
Έλμ μ : V(μ μ : Vertex) μ΄μμ μ : E(κ°μ : Edge)λΌκ³ ν λ
TC : O(V + E)
λ
Έλμ μ΄μμ λν΄μ μννλ―λ‘
SC : O(V + E)
ν΄μν
μ΄λΈμ ν¬κΈ°κ° λ
Έλμ μμ λΉλ‘ν΄μ 컀μ§κ³
dfsμ νΈμΆμ€νμ μ΄μμ μλ§νΌ μμ΄λ―λ‘
"""
"""
# 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 []
"""
from typing import Optional
class Solution:
def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:
if not node :
return None
clones = {}
def dfs(node : Optional['Node']) -> Optional['Node']:
if node in clones :
return clones[node]
clone = Node(node.val)
clones[node] = clone
for nei in node.neighbors :
clone.neighbors.append(dfs(nei))
return clone
return dfs(node)