lintcode-medium-Clone Graph

Posted 哥布林工程师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
    }
}

 

以上是关于lintcode-medium-Clone Graph的主要内容,如果未能解决你的问题,请参考以下文章

P3507 [POI2010]GRA-The Minima Game

[POI2010]GRA-The Minima Game

灰色关联度分析法(GRA)_python

floyd算法

数学建模之灰色关联分析(GRA)

关于layout_centerHorizontallayout_gravitygravity的区别