这个题不会做
class Node:
def __init__(self, val=0, neighbors=None):
self.val = val
self.neighbors = neighbors if neighbors is not None else []
class Solution(object):
def __init__(self):
self.visited = {}
def cloneGraph1(self, node):
"""
:type node: Node
:rtype: Node
"""
if not node:
return node
if node in self.visited:
return self.visited[node]
clone_node = Node(node.val, [])
self.visited[node] = clone_node
neb_list = []
for neb in node.neighbors:
neb_list.append(self.cloneGraph(neb))
clone_node.neighbors = neb_list
return clone_node
def cloneGraph2(self, node):
"""BFS遍历
:type node: Node
:rtype: Node
"""
if not node:
return node
self.visited[node] = Node(node.val)
queue = [node]
while queue:
first_node = queue.pop(0)
for neb in first_node.neighbors:
if neb not in self.visited:
self.visited[neb] = Node(neb.val)
queue.append(neb)
self.visited[first_node].neighbors.append(self.visited[neb])
return self.visited[node]
if __name__ == '__main__':
adjList = [[2, 3, 4], [1, 3], [1, 2, 4], [1, 3]]
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node4 = Node(4)
node1.neighbors.append(node2)
node1.neighbors.append(node4)
node2.neighbors.append(node1)
node2.neighbors.append(node3)
node3.neighbors.append(node2)
node3.neighbors.append(node4)
node4.neighbors.append(node1)
node4.neighbors.append(node3)
s1 = Solution()
ret = s1.cloneGraph(node1)
print(ret)