# [leetcode]Clone Graph @ Python

dfs代码：

# Definition for a undirected graph node
# class UndirectedGraphNode:
#     def __init__(self, x):
#         self.label = x
#         self.neighbors = []

class Solution:
# @param node, a undirected graph node
# @return a undirected graph node
# @BFS
def cloneGraph(self, node):
def dfs(input, map):
if input in map:
return map[input]
output = UndirectedGraphNode(input.label)
map[input] = output
for neighbor in input.neighbors:
output.neighbors.append(dfs(neighbor, map))
return output
if node == None: return None
return dfs(node, {})

bfs代码：

# Definition for a undirected graph node
# class UndirectedGraphNode:
#     def __init__(self, x):
#         self.label = x
#         self.neighbors = []

class Solution:
# @param node, a undirected graph node
# @return a undirected graph node
# @BFS
def cloneGraph(self, node):
if node == None: return None
queue = []; map = {}
queue.append(node)
while queue:
curr = queue.pop()
for neighbor in curr.neighbors:
if neighbor not in map:
copy = UndirectedGraphNode(neighbor.label)
map[curr].neighbors.append(copy)
map[neighbor] = copy
queue.append(neighbor)
else:
# turn directed graph to undirected graph
map[curr].neighbors.append(map[neighbor])
return newhead

posted @ 2014-05-26 17:15  南郭子綦  阅读(4919)  评论(0编辑  收藏