[LeetCode] Clone Graph

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


OJ's undirected graph serialization:

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 #.

  1. First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
  2. Second node is labeled as 1. Connect node 1 to node 2.
  3. 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
         / \
         \_/


这题和之前Copy List with Random Pointer的思路类似,都是要使用一个hash map建立原始节点和新建节点之间的映射。思路上可以认为是遍历了graph两次:

1) clone all the labels;

2) clone all the edges.


不过这里两步其实完全可以合并为一步。例如使用BFS的话,碰到访问过的节点,直接在新的图里加上边即可;碰到未访问过的节点,生成新节点,加上边,并建立映射。

    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if (node == null) {
            return null;
        }
             
        // BFS.
        Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
        Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
        queue.offer(node);
        UndirectedGraphNode source = new UndirectedGraphNode(node.label);
        map.put(node, source);
        while (!queue.isEmpty()) {
            UndirectedGraphNode n = queue.poll();
            for (UndirectedGraphNode neighbor : n.neighbors) {
                if (!map.containsKey(neighbor)) {
                    // Construct a new copy, add an edge, and construct the mapping.
                    UndirectedGraphNode copyNode = new UndirectedGraphNode(neighbor.label);
                    map.get(n).neighbors.add(copyNode);
                    map.put(neighbor, copyNode);
                    
                    queue.offer(neighbor);
                } else {
                    // Add an edge.
                    map.get(n).neighbors.add(map.get(neighbor));
                }
            }
        }
        
        return source;
    }



你可能感兴趣的:(LeetCode,Graph,clone)