November 23, 2025
์ด ๋ฌธ์ ๋ ๋ฌด๋ฐฉํฅ ๊ทธ๋ํ๊ฐ ์ฃผ์ด์ง๋ฉด ํด๋น ๊ทธ๋ํ์ ๊น์ ๋ณต์ฌ๋ณธ์ ๋ง๋๋ ๋ฌธ์ ๋ค. ๊ฐ์ ๊ทธ๋ํ๋ฅผ ๋ฐํํ๋ฉด ์๋๊ณ , ๊ฐ ๋ ธ๋์ ๊ฐ์ ์ด ๋์ผํ ์๋ก์ด ๊ทธ๋ํ๋ฅผ ๋ง๋ค์ด์ผ ํ๋ค.
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
old_to_new = {}
def dfs(node):
if node in old_to_new:
return old_to_new[node]
copy = Node(node.val)
old_to_new[node] = copy
for neighbor in node.neighbors:
copy.neighbors.append(dfs(neighbor))
return copy
return dfs(node)
Constraints:
The number of nodes in the graph is in the range [0, 100].
1 <= Node.val <= 100
Node.val is unique for each node.
There are no repeated edges and no self-loops in the graph.
The Graph is connected and all nodes can be visited starting from the given node.