Clone Graph

来源:互联网 发布:数据来源有哪些 编辑:程序博客网 时间:2024/05/17 05:13

Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.

How we serialize an undirected graph:

Nodes are labeled uniquely.

We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.

As an example, consider the serialized graph {0,1,2#1,2#2,2}.

The graph has a total of three nodes, and therefore contains three parts as separated by #.

First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
Second node is labeled as 1. Connect node 1 to node 2.
Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.
Visually, the graph looks like the following:

1
/ \
/ \
0 — 2
/ \
_/

这个题目不要追求简单,一定要追求程序的健壮性,因此要先复制点,然后在复制边。切记分开进行。
by:在进行深拷贝时,一定是复制后的点与复制后的点相连接,而非与复制前的点相连接!!!
java

/** * Definition for undirected graph. * class UndirectedGraphNode { *     int label; *     ArrayList<UndirectedGraphNode> neighbors; *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); } * }; */public class Solution {    /*     * @param node: A undirected graph node     * @return: A undirected graph node     */    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {        // write your code here        if (node == null) {            return null;        }        Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<>();        Queue<UndirectedGraphNode> queue = new LinkedList<>();        Set<UndirectedGraphNode> set = new HashSet<>();        queue.offer(node);        set.add(node);        // copy node        while (!queue.isEmpty()) {            UndirectedGraphNode root = queue.poll();            if (!map.containsKey(root)) {                map.put(root, new UndirectedGraphNode(root.label));            }            for (UndirectedGraphNode val: root.neighbors) {                if (!set.contains(val)) {                    queue.offer(val);                    set.add(val);                }            }        }        // copy edges        for (UndirectedGraphNode root: map.keySet()) {            for (UndirectedGraphNode val: root.neighbors) {                map.get(root).neighbors.add(map.get(val));            }        }        return map.get(node);    }}

python

"""Definition for a undirected graph nodeclass UndirectedGraphNode:    def __init__(self, x):        self.label = x        self.neighbors = []"""import Queueclass Solution:    """    @param: node: A undirected graph node    @return: A undirected graph node    """    def cloneGraph(self, node):        # write your code here        if node is None:            return None        table = self.getNode(node)        mapping = {}        for ele in table:            mapping[ele] = UndirectedGraphNode(ele.label)        for ele in table:            for val in ele.neighbors:                mapping[ele].neighbors.append(mapping[val])        return mapping[node]    def getNode(self, node):        queue = Queue.Queue()        table = set()        queue.put(node)        table.add(node)        while not queue.empty():            root = queue.get()            for ele in root.neighbors:                if ele in table:                    continue                else:                    queue.put(ele)                    table.add(ele)        return table
原创粉丝点击