qingcheng奕  

https://oj.leetcode.com/problems/clone-graph/

图的拷贝,就是给一个图,再弄出一个一模一样的来。

/**
 * Definition for undirected graph.
 * struct UndirectedGraphNode {
 *     int label;
 *     vector<UndirectedGraphNode *> neighbors;
 *     UndirectedGraphNode(int x) : label(x) {};
 * };
 */
class Solution {
public:
    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
        if(node == NULL)
            return node;
        
        vector<UndirectedGraphNode *> allNode;
        unordered_map<UndirectedGraphNode *, UndirectedGraphNode *> oldToNew;
        
        // 对于每一个node,都建立一个新node,把这关系存到map里面。之后对每个旧node,添加相应新node里的neighbour
        
        allNode.push_back(node);
        UndirectedGraphNode *newNode = new UndirectedGraphNode(node->label);
        oldToNew.insert(make_pair(node,newNode));
                
        int index = 0;
        UndirectedGraphNode *current;
        UndirectedGraphNode *neighNode;
        vector<UndirectedGraphNode *> neighbours;
        // build new nodes
        while(index < allNode.size())
        {
            current = allNode[index];
            index++;
            neighbours = current->neighbors;
            
            for(int i = 0; i < neighbours.size(); i++)
            {
                neighNode = neighbours[i];
                // 之前没有添加过它相应的
                if(oldToNew.find(neighNode) == oldToNew.end())
                {
                    UndirectedGraphNode *newNode = new UndirectedGraphNode(neighNode->label);
                    oldToNew.insert(make_pair(neighNode,newNode));
                    
                    allNode.push_back(neighNode);
                }
            }
        }
        // build neighbours
        unordered_map<UndirectedGraphNode *, UndirectedGraphNode *>::iterator itr;
        for(itr = oldToNew.begin(); itr!=oldToNew.end(); itr++)
        {
            current = itr->first;
            neighbours = current->neighbors;
            for(int i = 0; i < neighbours.size(); i++)
            {
                itr->second->neighbors.push_back(oldToNew[neighbours[i]]);
            }
        }
        return oldToNew[node];
    }
};

 

posted on 2014-08-16 22:22  qingcheng奕  阅读(132)  评论(0编辑  收藏  举报