[和小菜鸡一起刷题(python)] LeetCode 133. 克隆图(clone-graph)

LeetCode 133. 克隆图 (clone-graph)

  • 原题
  • 思路
  • 代码

原题

克隆一张无向图,图中的每个节点包含一个 label (标签)和一个 neighbors (邻接点)列表 。

OJ的无向图序列化:

节点被唯一标记。

我们用 # 作为每个节点的分隔符,用 , 作为节点标签和邻接点的分隔符。

例如,序列化无向图 {0,1,2#1,2#2,2}。

该图总共有三个节点, 被两个分隔符 # 分为三部分。

第一个节点的标签为 0,存在从节点 0 到节点 1 和节点 2 的两条边。
第二个节点的标签为 1,存在从节点 1 到节点 2 的一条边。
第三个节点的标签为 2,存在从节点 2 到节点 2 (本身) 的一条边,从而形成自环。
我们将图形可视化如下:

   1
  / \
 /   \
0 --- 2
     / \
     \_/

思路

此题思路比较简单,先建立节点,再连接节点。
先克隆每个节点的label,同时建立克隆后的老节点与新节点的对应关系。在所有节点克隆完成后遍历所有新节点,依次按照对应关系给节点的neighbors赋值。

代码

# 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
    def cloneGraph(self, node):
        if not node:
            return None
        else:
            mapping = dict()
            self.clone(node, mapping)
            for old_node, new_node in zip(mapping.keys(),mapping.values()):
                new_node.neighbors = [mapping[x] for x in old_node.neighbors]
            return mapping[node]

    def clone(self, node, mapping):
        if node not in mapping:
            node_clone = UndirectedGraphNode(node.label)
            mapping[node] = node_clone
            for n in node.neighbors:
                self.clone(n, mapping)

你可能感兴趣的:(小菜鸡刷LeetCode)