|
| 1 | +""" |
| 2 | +Constraints: |
| 3 | +- The number of nodes in the graph is in the range [0, 100]. |
| 4 | +- 1 <= Node.val <= 100 |
| 5 | +- Node.val is unique for each node. |
| 6 | +- There are no repeated edges and no self-loops in the graph. |
| 7 | +- The Graph is connected and all nodes can be visited starting from the given node. |
| 8 | +
|
| 9 | +Shallow Copy (์์ ๋ณต์ฌ): |
| 10 | +- ๋
ธ๋ ์์ฒด๋ ์๋ก์ด ๋ฉ๋ชจ๋ฆฌ์ ๋ณต์ฌ |
| 11 | +- ํ์ง๋ง neighbors๋ ์๋ณธ ๋
ธ๋์ neighbors๋ฅผ ๊ทธ๋๋ก ์ฐธ์กฐ |
| 12 | +์์) ์๋ณธ Node1์ด Node2๋ฅผ neighbor๋ก ๊ฐ์ง ๋ |
| 13 | + ๋ณต์ฌํ CopyNode1์ ์๋ก์ด ๋
ธ๋์ง๋ง |
| 14 | + CopyNode1์ neighbor๋ ์๋ณธ์ Node2๋ฅผ ๊ทธ๋๋ก ๊ฐ๋ฆฌํด |
| 15 | +
|
| 16 | +Deep Copy (๊น์ ๋ณต์ฌ): |
| 17 | +- ๋
ธ๋๋ ์๋ก์ด ๋ฉ๋ชจ๋ฆฌ์ ๋ณต์ฌ |
| 18 | +- neighbors๋ ๋ชจ๋ ์๋ก์ด ๋
ธ๋๋ก ๋ณต์ฌํด์ ์ฐ๊ฒฐ |
| 19 | +์์) ์๋ณธ Node1์ด Node2๋ฅผ neighbor๋ก ๊ฐ์ง ๋ |
| 20 | + CopyNode1๋ ์๋ก์ด ๋
ธ๋์ด๊ณ |
| 21 | + CopyNode1์ neighbor๋ ์๋ก ๋ง๋ CopyNode2๋ฅผ ๊ฐ๋ฆฌํด |
| 22 | +
|
| 23 | +Time Complexity: O(N + E) |
| 24 | +- N: ๋
ธ๋์ ๊ฐ์ |
| 25 | +- E: ์ฃ์ง์ ๊ฐ์ |
| 26 | +- ๋ชจ๋ ๋
ธ๋์ ์ฃ์ง๋ฅผ ํ ๋ฒ์ฉ ๋ฐฉ๋ฌธ |
| 27 | +
|
| 28 | +Space Complexity: O(N) |
| 29 | +- N: ๋
ธ๋์ ๊ฐ์ |
| 30 | +- dictionary์ ์ฌ๊ท ํธ์ถ ์คํ ๊ณต๊ฐ |
| 31 | +
|
| 32 | +# Definition for a Node. |
| 33 | +class Node: |
| 34 | + def __init__(self, val = 0, neighbors = None): |
| 35 | + self.val = val |
| 36 | + self.neighbors = neighbors if neighbors is not None else [] |
| 37 | +
|
| 38 | +์ฐธ๊ณ ์ฌํญ: |
| 39 | +- ํผ์ ํ๊ธฐ ์ด๋ ค์์, ๋ฌธ์ ์ ๋ต์ ์ดํดํ๋ ๊ฒ์ ์ง์คํ์ต๋๋ค! |
| 40 | +""" |
| 41 | +class Solution: |
| 42 | + def cloneGraph(self, node: Optional['Node']) -> Optional['Node']: |
| 43 | + if not node: |
| 44 | + return None |
| 45 | + |
| 46 | + dict = {} |
| 47 | + |
| 48 | + def dfs(node): |
| 49 | + if node.val in dict: # ์ด๋ฏธ ๋ณต์ฌํ ๋
ธ๋๋ผ๋ฉด |
| 50 | + return dict[node.val] # ํด๋น ๋ณต์ฌ๋ณธ ๋ฐํ |
| 51 | + |
| 52 | + # ์๋ก์ด ๋
ธ๋ ์์ฑ |
| 53 | + copy = Node(node.val) |
| 54 | + dict[node.val] = copy # dictionary์ ๊ธฐ๋ก |
| 55 | + |
| 56 | + # ๊ฐ neighbor์ ๋ํด์๋ ๊ฐ์ ๊ณผ์ ์ํ |
| 57 | + for neighbor in node.neighbors: |
| 58 | + copy.neighbors.append(dfs(neighbor)) |
| 59 | + |
| 60 | + return copy |
| 61 | + |
| 62 | + return dfs(node) |
| 63 | + |
0 commit comments