Skip to content

Commit 3e21a44

Browse files
committed
clone-graph solution
1 parent d3b665e commit 3e21a44

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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)

0 commit comments

Comments
ย (0)