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
  • 相关阅读:
    UPDATE 时主键冲突引发的思考【转】
    MySQL Sandbox安装使用
    主从复制1062错误解决方法
    InnoDB log file 设置多大合适?
    EXPLAIN 命令详解
    【机器学习】ID3算法构建决策树
    连续属性离散化处理
    【机器学习】决策树基础知识
    【机器学习】模型评估与选择
    【机器学习】单层感知器
  • 原文地址:https://www.cnblogs.com/zuoyuan/p/3753507.html
Copyright © 2011-2022 走看看