lintcode-medium-Clone Graph

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

思路:

分为两步

1. BFS,新建所有图中的node,用一个HashMap建立原来node和新的node之间的对应关系

2. 再遍历所有原有的node,把新node中的neighbors填上对应的node

/**
 * 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;
        
        ArrayList<UndirectedGraphNode> nodes = new ArrayList<UndirectedGraphNode>();
        HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
        
        nodes.add(node);
        map.put(node, new UndirectedGraphNode(node.label));
        
        int start = 0;
        while(start < nodes.size()){
            UndirectedGraphNode temp = nodes.get(start++);
            for(int i = 0; i < temp.neighbors.size(); i++){
                UndirectedGraphNode neighbor = temp.neighbors.get(i);
                if(!map.containsKey(neighbor)){
                    nodes.add(neighbor);
                    map.put(neighbor, new UndirectedGraphNode(neighbor.label));
                }
            }
        }
        
        for(int i = 0; i < nodes.size(); i++){
            UndirectedGraphNode temp = nodes.get(i);
            
            for(int j = 0; j < temp.neighbors.size(); j++){
                map.get(temp).neighbors.add(map.get(temp.neighbors.get(j)));
            }
        }
        
        return map.get(node);
    }
}

 

posted @ 2016-03-15 13:20  哥布林工程师  阅读(184)  评论(0编辑  收藏  举报