- 克隆圖
中文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