133. Clone Graph

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


OJ's undirected graph serialization:
Nodes are labeled uniquely.

We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.
As an example, consider the serialized graph {0,1,2#1,2#2,2}.

The graph has a total of three nodes, and therefore contains three parts as separated by #.

First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
Second node is labeled as 1. Connect node 1 to node 2.
Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.
Visually, the graph looks like the following:

       1
      / \
     /   \
    0 --- 2
         / \
         \_/
克隆圖的一個難點就是一個結點的鄰居可能在已經出現過,這樣你只要把他的指針加到鄰居集合中即可,
也有可能這個結點還沒出現過,因此你需要新建一個這個結點,因此我們需要一個hash表來對結點做一一映射
每次搜索的時候看這個結點是不是已經被創建,是的話就返回其copy,否則就創建,然後再依次深度遍歷
其鄰居結點並將其加入鄰居集合中去.

*/



/**
 * 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) return NULL;
        unordered_map<UndirectedGraphNode*,UndirectedGraphNode*> mp;
        return clone(node,mp);
    }
    UndirectedGraphNode *clone(UndirectedGraphNode *node,unordered_map<UndirectedGraphNode*,UndirectedGraphNode*>&mp){
        if(!node) return NULL;
        if(mp.find(node)!=mp.end())//查看節點是否已經生成
            return mp[node];
        mp[node]=new UndirectedGraphNode(node->label);
        for(auto n : node->neighbors)
            mp[node]->neighbors.push_back(clone(n,mp));
        return mp[node];
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章