Clone Graph 07/30

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

  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
     / \
     \_/

Have you met this question in a real interview? Yes

Example

return a deep copied graph.

先把图里的所有node,用宽度有限搜索存起来,然后用hashmap建立旧node和新node的一一对应,然后遍历每一个node的邻居,根据这个邻居,来找到对应的信建立的node,也就是map的value,然后把找到的对应的旧邻居的新邻居,加到对应的点的邻居队列里

/**
 * 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 node;
        }
        
        List<UndirectedGraphNode> list = getNodeList(node);
        
        
        HashMap<UndirectedGraphNode,UndirectedGraphNode> map = new HashMap<>();
        
        
        for(UndirectedGraphNode n : list){
            map.put(n,new UndirectedGraphNode(n.label));
        }
        
        
        for(UndirectedGraphNode n : list){
            ArrayList<UndirectedGraphNode> nei = n.neighbors;
             UndirectedGraphNode newNode = map.get(n);
            for(UndirectedGraphNode m : nei){
               UndirectedGraphNode newNeib = map.get(m);
               newNode.neighbors.add(newNeib);
                
            }
        }
        
        return map.get(node);
    }
    
    public List<UndirectedGraphNode> getNodeList(UndirectedGraphNode node){
        
        Queue<UndirectedGraphNode> queue = new LinkedList<>();
        Set<UndirectedGraphNode> set = new HashSet<>();
        
        queue.offer(node);
        set.add(node);
        
        while(!queue.isEmpty()){
            UndirectedGraphNode top = queue.poll();
            
            for(UndirectedGraphNode n : top.neighbors){
                if(!set.contains(n)){
                    set.add(n);
                    queue.offer(n);
                }
            }
            
            
        }
        
        return new ArrayList<UndirectedGraphNode>(set);
    }
}

Last updated