< All posts

133. Clone Graph

๋ฌธ์ œ ์„ค๋ช…

์ด ๋ฌธ์ œ๋Š” ๋ฌด๋ฐฉํ–ฅ ๊ทธ๋ž˜ํ”„๊ฐ€ ์ฃผ์–ด์ง€๋ฉด ํ•ด๋‹น ๊ทธ๋ž˜ํ”„์˜ ๊นŠ์€ ๋ณต์‚ฌ๋ณธ์„ ๋งŒ๋“œ๋Š” ๋ฌธ์ œ๋‹ค. ๊ฐ™์€ ๊ทธ๋ž˜ํ”„๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋ฉด ์•ˆ๋˜๊ณ , ๊ฐ ๋…ธ๋“œ์™€ ๊ฐ„์„ ์ด ๋™์ผํ•œ ์ƒˆ๋กœ์šด ๊ทธ๋ž˜ํ”„๋ฅผ ๋งŒ๋“ค์–ด์•ผ ํ•œ๋‹ค.

133

ํ’€์ด ๋ฐ ํ•ด์„ค

DFS๋ฅผ ์ด์šฉํ•˜์—ฌ ๊ทธ๋ž˜ํ”„๋ฅผ ์ˆœํšŒํ•˜๋ฉด์„œ ๊ฐ ๋…ธ๋“œ๋ฅผ ๋ณต์‚ฌํ•˜๊ณ , ๋ณต์‚ฌ๋œ ๋…ธ๋“œ๋“ค์„ ์—ฐ๊ฒฐํ•ด์ฃผ๋ฉด ๋œ๋‹ค.

  • ๋”•์…”๋„ˆ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์›๋ณธ ๋…ธ๋“œ์™€ ๋ณต์‚ฌ๋œ ๋…ธ๋“œ ๊ฐ„์˜ ๋งคํ•‘์„ ์ €์žฅํ•œ๋‹ค.
  • 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)

Complexity Analysis

1

์‹œ๊ฐ„ ๋ณต์žก๋„

  • O(N + M) , N์€ ๋…ธ๋“œ์˜ ์ˆ˜, M์€ ๊ฐ„์„ ์˜ ์ˆ˜

๊ณต๊ฐ„ ๋ณต์žก๋„

  • O(N)

Constraint Analysis

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.

References

ยฉ 2025 HyunJoon Sung. All Rights Reserved.

GitHub