给出连接的无向图中节点的引用,返回该图的深层副本(克隆)。图中的每个节点都包含一个val(int)和其邻居的列表(List [Node])。 https://leetcode.com/problems/clone-graph/
试图通过leetcode解决此问题,并且不确定确切的位置以及如何找到正确的解决方案
示例:
class Solution(object):
def cloneGraph(self, node):
newNode = Node(node.val, [])
oldNode = node
dic = {}
dic[oldNode] = newNode
bfs = [oldNode]
while bfs:
oldNode = bfs.pop(0)
newNode = dic[oldNode]
neighbors = []
for item in oldNode.neighbors:
if item not in dic:
copy = Node(item.val, [])
dic[item] = copy
neighbors.append(copy)
bfs.append(item)
else:
copy = dic[item]
neighbors.append(copy)
newNode.neighbors = neighbors
return newNode
答案 0 :(得分:0)
将最后一行更改为
return dic[node]
,它将起作用。首先,您需要返回发送给函数的节点的克隆节点,而newNode
是之前经历while bfs:
循环时,它在更改期间循环。