- 克隆图
中文English
克隆一张无向图. 无向图的每个节点包含一个 label 和一个列表 neighbors. 保证每个节点的 label 互不相同.
你的程序需要返回一个经过深度拷贝的新图. 新图和原图具有同样的结构, 并且对新图的任何改动不会对原图造成任何影响.
Example
样例1
输入:
{1,2,4#2,1,4#4,1,2}
输出:
{1,2,4#2,1,4#4,1,2}
解释:
1------2
\ |
\ |
\ |
\ |
4
Clarification
关于无向图的表示: http://www.lintcode.com/help/graph/
Notice
你需要返回与给定节点具有相同 label 的那个节点
Python bfs思想
"""
class UndirectedGraphNode:
def __init__(self, x):
self.label = x
self.neighbors = []
"""
class Solution:
"""
@param node: A undirected graph node
@return: A undirected graph node
"""
def cloneGraph(self, node):
root = node
if node is None:
return node
# use bfs algorithm to traverse the graph and get all nodes
nodes = self.getNodes(node)
print("hello")
# copy node, store the old -> new mapping information in a hash map
mapping = {}
for node in nodes:
mapping[node] = UndirectedGraphNode(node.label)
# copy neighbors(edge)
for node in nodes:
new_node = mapping[node]
for neighbor in node.neighbors:
new_neighbor = mapping[neighbor]
new_node.neighbors.append(new_neighbor)
return mapping[root]
def getNodes(self, node):
q = collections.deque([node])
result = set([node])
while q:
head = q.popleft()
for neighbor in head.neighbors:
if neighbor not in result:
result.add(neighbor)
q.append(neighbor)
return result