【leetcode】133. Clone Graph

亦凉 2022-01-10 06:09 226阅读 0赞

题目如下:

Given the head of a graph, return a deep copy (clone) of the graph. Each node in the graph contains a label (int) and a list (List[UndirectedGraphNode]) of its neighbors. There is an edge between the given node and each of the nodes in its neighbors.

OJ’s undirected graph serialization (so you can understand error output):

Nodes are labeled uniquely.

We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.

As an example, consider the serialized graph { 0,1,2#1,2#2,2}.

The graph has a total of three nodes, and therefore contains three parts as separated by #.

  1. First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
  2. Second node is labeled as 1. Connect node 1 to node 2.
  3. Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.

Visually, the graph looks like the following:

  1. 1
  2. / \
  3. / \
  4. 0 --- 2
  5. / \
  6. \_/

Note: The information about the tree serialization is only meant so that you can understand error output if you get a wrong answer. You don’t need to understand the serialization to solve the problem.

解题思路:深拷贝node。题目本身不难,由于所有节点的lable都是唯一的,因此需要保持已经创建过节点的lable,避免出现重复创建。另外节点存在self-cycle,所以遍历过的路径也需要保存。

代码如下:

  1. # Definition for a undirected graph node
  2. class UndirectedGraphNode:
  3. def __init__(self, x):
  4. self.label = x
  5. self.neighbors = []
  6. class Solution:
  7. # @param node, a undirected graph node
  8. # @return a undirected graph node
  9. def cloneGraph(self, node):
  10. if node == None:
  11. return None
  12. root = UndirectedGraphNode(node.label)
  13. queue = [(node,root)]
  14. dic = {}
  15. dic[root.label] = root
  16. dic_visit = {}
  17. while len(queue) > 0:
  18. n,r = queue.pop(0)
  19. if n.label in dic_visit:
  20. continue
  21. for i in n.neighbors:
  22. if i.label not in dic:
  23. i_node = UndirectedGraphNode(i.label)
  24. dic[i.label] = i_node
  25. else:
  26. i_node = dic[i.label]
  27. r.neighbors.append(i_node)
  28. queue.append((i, r.neighbors[-1]))
  29. dic_visit[n.label] = 1
  30. return root

转载于:https://www.cnblogs.com/seyjs/p/10214867.html

发表评论

表情:
评论列表 (有 0 条评论,226人围观)

还没有评论,来说两句吧...

相关阅读

    相关 leetcode133. Clone Graph

    133. Clone Graph ![这里写图片描述][SouthEast] 这道题目的意思是:对一个无向图进行深拷贝,即需要申请一个新的空间,并将原来的无向图中的节点