Notice
Recent Posts
Recent Comments
Link
오늘도 개발
42. Clone Graph(dfs) 본문
문제
연결 그래프를 인수로 받아 deep copy하여 반환하시오.
해결 방식
1) 노드 값 먼저 복사(dfs로)
2) 노드 neighbors 추가
class Solution:
def cloneGraph(self, node):
# '키 : 값'은 '원래 그래프에 있는 노드의 주소값 : deep copy된 노드(=새 주소에 생성된 값만 같은 노드)'
mapping = {}
# neighbor도 복사한 노드의 모음
rebuilt = set()
def dfs_copy(node):
if id(node) in mapping:
return
# 현재 노드의 deep copy 생성, neighbors는 빈 값으로 둠
mapping[id(node)] = Node(val=node.val, neighbors=[])
for original_neighbor in node.neighbors:
# 현재 노드의 이웃 노드의 deep copy 생성
dfs_copy(original_neighbor)
def dfs_rebuild_neighbor(node):
if node in rebuilt:
return
for original_neighbor in node.neighbors:
# mapping에 있는 deep copy된 노드의 neighbors에 deep copy된 이웃 노드 추가
mapping[id(node)].neighbors.append(mapping[id(original_neighbor)])
rebuilt.add(node)
for original_neighbor in node.neighbors:
dfs_rebuild_neighbor(original_neighbor)
if node:
# 1) 노드 값 먼저 복사
dfs_copy(node)
# 2) 노드 neighbors 추가
dfs_rebuild_neighbor(node)
return mapping[id(node)]
else:
return None'자료구조 & 알고리즘 > Leetcode' 카테고리의 다른 글
| 44. Implement Queue using Stacks (0) | 2022.11.12 |
|---|---|
| 43. Target Sum (0) | 2022.11.09 |
| 41. Min Stack (0) | 2022.10.31 |
| 40. Perfect Squares(bfs) (1) | 2022.10.29 |
| 39. Open the Lock(bfs) (0) | 2022.10.28 |