traverse graph (Breadth First Search)
copy using HashMap
# Definition for a undirected graph node
# class UndirectedGraphNode(object):
# def __init__(self, x):
# self.label = x
# self.neighbors = []
class Solution(object):
def cloneGraph(self, node):
"""
:type node: UndirectedGraphNode
:rtype: UndirectedGraphNode
"""
if node is None:
return None
#if graph is not empty, make a copy of the first node
cloned_node=UndirectedGraphNode(node.label)
#create a hashmap with key=node in the original graph,value=cloned node
cloned={node:cloned_node}
#store the next level of nodes to be visited
queue=[node]
while queue:
current=queue.pop()
#loop through the neighbours of the current node
for neighbor in current.neighbors:
#if the neighbor node hasn't been cloned before, make a clone
if neighbor not in cloned:
queue.append(neighbor)
cloned_neighbor=UndirectedGraphNode(neighbor.label)
cloned[neighbor]=cloned_neighbor
#attach the created neighbors to the current graph node
cloned[current].neighbors.append(cloned[neighbor])
return cloned[node]
网友评论