Saturday, July 11, 2015

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
         / \
         \_/
Have you met this question in a real interview? 
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;
        HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
        Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
        queue.offer(node);
        UndirectedGraphNode newNode = new UndirectedGraphNode(node.label);
        map.put(node, newNode);
        while(!queue.isEmpty()){
            UndirectedGraphNode cur = queue.poll();
            ArrayList<UndirectedGraphNode> neighbors = cur.neighbors;
            for(UndirectedGraphNode n : neighbors){
                if(map.containsKey(n)){
                    map.get(cur).neighbors.add(map.get(n));
                } else {
                    UndirectedGraphNode temp = new UndirectedGraphNode(n.label);
                    map.put(n, temp);
                    map.get(cur).neighbors.add(temp);
                    queue.offer(n);
                }
                
            }
            
        }
        return newNode;
    }
    
   
}

Yes

No comments:

Post a Comment