File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed
Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ # Definition for a Node.
3+ class Node:
4+ def __init__(self, val = 0, neighbors = None):
5+ self.val = val
6+ self.neighbors = neighbors if neighbors is not None else []
7+ """
8+
9+ from typing import Optional
10+ class Solution :
11+ def cloneGraph (self , node : Optional ['Node' ]) -> Optional ['Node' ]:
12+
13+ # ๊น์ ๋ณต์ฌ
14+ # DFS ์ด์ฉํ์ผ๋ ๋์ค์ BFS๋ก๋ ํด ๋ณผ ๊ฒ
15+ # ์๊ฐ๋ณต์ก๋ O(n), ๊ณต๊ฐ๋ณต์ก๋ O(n)
16+
17+ if not node :
18+ return None
19+
20+ # ์๋ณธ์์ ๋ณต์ฌ๋
ธ๋ ๋งคํ ์ ์ฅํ ๋์
๋๋ฆฌ
21+ copied = {}
22+
23+ def dfs (curr ):
24+ # ํ์ฌ ๋
ธ๋๊ฐ ๋ณต์ฌ๋ ๋
ธ๋๋ฉด ๊ทธ๋๋ก ๋ฆฌํด
25+ if curr in copied :
26+ return copied [curr ]
27+
28+ copy = Node (curr .val ) # ํ์ฌ ๋
ธ๋ ๋ณต์ฌ
29+ copied [curr ] = copy # ๋ณต์ฌ๋ณธ ์ ์ฅ
30+
31+ # ์ด์๋
ธ๋๋ค ๋ณต์ฌํด์ ์ฐ๊ฒฐ
32+ for i in curr .neighbors :
33+ copy .neighbors .append (dfs (i ))
34+
35+ return copy
36+
37+ return dfs (node )
You canโt perform that action at this time.
0 commit comments