Description:
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 val (int
) and a list (List[Node]
) of its neighbors.
Example:
Input:
{"id":"2","neighbors":[{"
id":"3","neighbors":[{"
id":"4","neighbors":[{"
ref":"1"}],"val":4}],"val":3}],"val":2},{"$ref":"4"}],"val":1}
Explanation:
Node 1's value is 1, and it has two neighbors: Node 2 and 4.
Node 2's value is 2, and it has two neighbors: Node 1 and 3.
Node 3's value is 3, and it has two neighbors: Node 2 and 4.
Node 4's value is 4, and it has two neighbors: Node 1 and 3.
Note:
- The number of nodes will be between 1 and 100.
- The undirected graph is a simple graph, which means no repeated edges and no self-loops in the graph.
- Since the graph is undirected, if node p has node q as neighbor, then node q must have node p as neighbor too.
- You must return the copy of the given node as a reference to the cloned graph.
Solution:
NOTE: BFS遍历graph,然后duplicate每一层的node。每一层内,挨个找下一层的节点(next_),遇到没有visited,新建一个新的node,把老node和新node放到hashtable(叫visited)里建立映射关系(给层内node之间的链接提供帮助),遇到遇见过的next_调用hashtable找到那个对应的新node。
中间没读懂题意,看到Node定义需要双变量输入,以为必须是offline建立图,卡了一会。
"""
# Definition for a Node.
class Node:
def __init__(self, val, neighbors):
self.val = val
self.neighbors = neighbors
"""
class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
node_ls = [node]
ret = Node(node.val,[])
visited = {node:ret}
node_ls2 = [ret]
def bfs(node_ls,node_ls2):
nonlocal visited
next_layer = []
next_layer2 = []
for i,n in enumerate(node_ls):
for next_ in n.neighbors:
if next_ not in visited:
next_layer2.append(Node(next_.val,[]))
next_layer.append(next_)
visited[next_] = next_layer2[-1]
node_ls2[i].neighbors.append(visited[next_])
if next_layer:
bfs(next_layer,next_layer2)
bfs(node_ls,node_ls2)
return ret
Runtime: 40 ms, faster than 96.53% of Python3 online submissions for Clone Graph.
Memory Usage: 14.4 MB, less than 5.70% of Python3 online submissions for Clone Graph.