forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsungjinwi.py
More file actions
44 lines (35 loc) ยท 1.33 KB
/
sungjinwi.py
File metadata and controls
44 lines (35 loc) ยท 1.33 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
"""
ํ์ด :
์ฌ๊ท๋ฅผ ์ด์ฉํด์ 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)