码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode-medium-Clone Graph

时间:2016-03-15 13:43:02      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

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);
    }
}

 

lintcode-medium-Clone Graph

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5279110.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!