【LeetCode 中等题】62-克隆图

题目描述:克隆一张无向图,图中的每个节点包含一个 label (标签)和一个 neighbors (邻接点)列表 。OJ的无向图序列化:节点被唯一标记。

我们用 # 作为每个节点的分隔符,用 , 作为节点标签和邻接点的分隔符。例如,序列化无向图 {0,1,2#1,2#2,2}

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

  1. 第一个节点的标签为 0,存在从节点 0 到节点 1 和节点 2 的两条边。
  2. 第二个节点的标签为 1,存在从节点 1 到节点 2 的一条边。
  3. 第三个节点的标签为 2,存在从节点 2 到节点 2 (本身) 的一条边,从而形成自环。

我们将图形可视化如下:

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

解法1。BFS方式,首先用队列的方式遍历所有节点,用dic的方式存储源节点和新节点的映射关系,然后遍历每个节点,通过键值更新键值。

# 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
        dic = {}
        q = [node]
        new_head = UndirectedGraphNode(node.label)
        dic[node] = new_head
        while q:
            cur = q.pop(0)
            for ne in cur.neighbors:
                if ne not in dic:
                    q.append(ne)
                    new_one = UndirectedGraphNode(ne.label)
                    dic[ne] = new_one
                dic[cur].neighbors.append(dic[ne])
        return new_head

解法2。DFS方式,代码和BFS很像,只是递归调用直至最深处最后一个元素,再回溯一个个,最先遍历的节点的最后被复制完善。

class Solution:
    # @param node, a undirected graph node
    # @return a undirected graph node
    def cloneGraph(self, node):
        if not node:
            return
        dic = {}
        new_head = UndirectedGraphNode(node.label)
        dic[node] = new_head
        self.dfs(node, dic)
        return new_head
    
    def dfs(self, node, dic):
        if not node:
            return
        for ne in node.neighbors:
            if ne not in dic:
                new_one = UndirectedGraphNode(ne.label)
                dic[ne] = new_one
                self.dfs(ne, dic)
            dic[node].neighbors.append(dic[ne])

参考链接:https://www.jianshu.com/p/f4cb4a9e7570

猜你喜欢

转载自blog.csdn.net/weixin_41011942/article/details/86214602
今日推荐