1957

无聊蛋疼的1957写的低端博客
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

[leetcode]Clone Graph

Posted on 2013-12-29 23:02  1957  阅读(520)  评论(0编辑  收藏  举报

建立一个映射,old_graph -> clone_graph 节点的映射。

如果不存在就新建,如果存在就把映射的节点push_back到neighbor里面

 

/**
 * 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 == nullptr ) return nullptr;
        unordered_map<UndirectedGraphNode * , UndirectedGraphNode *> otn;
        otn[node] = new UndirectedGraphNode(node -> label);
        queue<UndirectedGraphNode *> que;
        que.push(node);
        
        while(!que.empty()){
            UndirectedGraphNode* node = que.front() ; que.pop();
            int size = node -> neighbors.size();
            
            for(int i = 0 ; i < size ; i ++){
                if(otn.find(node -> neighbors[i]) == otn.end()){
                    UndirectedGraphNode * tmp = new UndirectedGraphNode(node -> neighbors[i] -> label);
                    otn[node] -> neighbors.push_back(tmp);
                    otn[node -> neighbors[i]] = tmp;
                    que.push(node -> neighbors[i]);
                }else{
                    otn[node] -> neighbors.push_back(otn[node -> neighbors[i]]);
                }
            }
        }
        return otn[node];
    }
};