zoukankan      html  css  js  c++  java
  • [leetcode]Clone Graph @ Python

    原题地址:https://oj.leetcode.com/problems/clone-graph/

    题意:实现对一个图的深拷贝。

    解题思路:由于遍历一个图有两种方式:bfs和dfs。所以深拷贝一个图也可以采用这两种方法。不管使用dfs还是bfs都需要一个哈希表map来存储原图中的节点和新图中的节点的一一映射。map的作用在于替代bfs和dfs中的visit数组,一旦map中出现了映射关系,就说明已经复制完成,也就是已经访问过了。

    dfs代码:

    # 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
        # @BFS
        def cloneGraph(self, node):
            def dfs(input, map):
                if input in map:
                    return map[input]
                output = UndirectedGraphNode(input.label)
                map[input] = output
                for neighbor in input.neighbors:
                    output.neighbors.append(dfs(neighbor, map))
                return output
            if node == None: return None
            return dfs(node, {})

    bfs代码:

    # 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
        # @BFS
        def cloneGraph(self, node):
            if node == None: return None
            queue = []; map = {}
            newhead = UndirectedGraphNode(node.label)
            queue.append(node)
            map[node] = newhead
            while queue:
                curr = queue.pop()
                for neighbor in curr.neighbors:
                    if neighbor not in map:
                        copy = UndirectedGraphNode(neighbor.label)
                        map[curr].neighbors.append(copy)
                        map[neighbor] = copy
                        queue.append(neighbor)
                    else:
                        # turn directed graph to undirected graph
                        map[curr].neighbors.append(map[neighbor])
            return newhead
  • 相关阅读:
    Linux系统启动流程
    linux系统目录介绍
    Nginx 安装配置教程
    深入理解linux系统的目录结构
    Mac 下安装Ruby环境(转)
    Android逆向之旅---SO(ELF)文件格式详解(转)
    TAG-9F10 发卡行相关数据(转)
    公钥,私钥,数字证书,签名,加密,认证,的概念区分(转)
    PBOC~PPT-补充内容B(转)
    PBOC~PPT-补充A(转)
  • 原文地址:https://www.cnblogs.com/zuoyuan/p/3753507.html
Copyright © 2011-2022 走看看