LeetCode Clone Graph

LeetCode解题之Clone Graph


原题

对一个无向图进行复制,图中的每一个节点都有自己的标签和自己相邻节点的列表。

注意点:

例子:

输入:

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

输出:

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

解题思路

因为图中可能存在环,所以直接将节点和它的相邻节点进行复制,并对它的相邻节点进行相同操作可能会进入死循环。为了避免循环访问,要对已经复制过的节点进行缓存,我们通过一个由标志和节点组成的字典来记录已经访问过的节点。当我们通过相邻关系来访问一个节点时,如果它是第一次被访问,则要将其加入一个栈中,在栈中的元素表示要继续访问它相邻的元素,并记录它已经被访问过,同时要跟新已经被访问过的节点中与其相邻的节点的邻居列表。当栈为空时,表示所有的节点都已经访问完毕,图也复制成功。

AC源码

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


class Solution(object):
    def cloneGraph(self, node):
        """
        :type node: UndirectedGraphNode
        :rtype: UndirectedGraphNode
        """
        if not node:
            return node
        visited = {}
        first = UndirectedGraphNode(node.label)
        visited[node.label] = first
        stack = [node]
        while stack:
            top = stack.pop()
            for n in top.neighbors:
                if n.label not in visited:
                    visited[n.label] = UndirectedGraphNode(n.label)
                    stack.append(n)
                visited[top.label].neighbors.append(visited[n.label])
        return first


if __name__ == "__main__":
    None

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值