Given a reference of a node in a connected undirected graph.
Return a deep copy (clone) of the graph.
Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors.
class Node {
public int val;
public List<Node> neighbors;
}
Test case format:
For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with val == 1, the second node with val == 2, and so on. The graph is represented in the test case using an adjacency list.
An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.
The given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph.
from typing import Optional
from collections import deque
class Solution:
def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:
if not node:
return node
q = deque([node])
answer = {node: Node(node.val)}
while q:
now = q.popleft()
for next_node in now.neighbors:
if next_node not in answer:
q.append(next_node)
answer[next_node] = Node(next_node.val)
answer[now].neighbors.append(answer[next_node])
return answer[node]
class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
if not node:
return node
answer = {}
def dfs(now):
if now in answer: # 이미 존재하는 node라면 return clone graph
return answer[now]
clone = Node(now.val) # 현재 노드
answer[now] = clone # 그래프에 생성
for next_node in now.neighbors: # 인접합 노드 탐색
clone.neighbors.append(dfs(next_node))
return clone
return dfs(node)
dfs로 풀이한 다른 코드를 참고하였다. leet code에서 이러한 문제가 종종 나오는데.. input output을 테스트하기 어렵다. 개인적으로는 좋은 문제인지 모르겠다.