133. Clone Graph

来源:互联网 发布:小米网络解锁 编辑:程序博客网 时间:2024/05/18 03:25
/*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];    }};
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 买的股票跌停了怎么办 刚买了万科天地怎么办 所持股票停牌怎么办 武钢股份退市股票怎么办 买了退市的股票怎么办 国际e庄租期到了怎么办 被汉藏文化骗了怎么办 杏仁吃多了中毒怎么办 出轨怀孕了该怎么办呢 瑞安医保卡丢了怎么办 包裹一直在揽收怎么办 揽收超时的快件怎么办 快递被别人偷了怎么办 行驶证副本丢了怎么办 眼睛进了石灰粉怎么办 高铁网上没票了怎么办 限行尾号是字母怎么办 手指被刺扎肿了怎么办 手上进了小刺怎么办 招投标标书丢了怎么办 冒险岛2装备红了怎么办 宝宝屁股腌红了怎么办 宝宝肛门红痒怎么办啊 宝宝屁屁溃烂了怎么办 脸过敏起红疙瘩怎么办 一岁宝宝屁股红怎么办 屁眼肉凸出来了怎么办 陶笛声音变闷了怎么办 吃三七粉上火了怎么办 红枣核吞下去了怎么办 话梅核吞下去了怎么办 芒果和海鲜吃了怎么办 小孩咳嗽喉咙有痰怎么办 4岁宝宝喉咙有痰怎么办 20天新生儿有痰怎么办 孩子嗓子老是有痰怎么办 买的哈密瓜不甜怎么办 吉他琴颈变形了怎么办 hcg值长得慢怎么办 蚊子老在耳边叫怎么办 刚买来的鲜海参怎么办