算法作业_41(2017.6.24第十八周)

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 #.

  1. First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
  2. Second node is labeled as 1. Connect node 1 to node 2.
  3. 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
         / \
         \_/
解析:复制一个图,为了保证没有重复元素,用hashmap存储(key不能重复),首先,这道题目不能直接返回node,因为需要克隆,也就意味着要为所有的节点心分配空间。其次,分析节点的元素,包括label和neighbors两项,这意味着完成一个节点需要克隆一个int和一个vector<UndirectedGraphNode *>。我们根据参数中的node提取出其label值,然后用构造方法生成一个节点,这样就完成了一个节点的生成。然后,根据参数中的node提取其neighbors中的元素,我们只需要把这些元素加入刚生成的节点中,便完成了第一个节点的克隆。再次,neighbor元素怎么生成呢?同样需要克隆。这样我们就可以总结出递归的思路。最后,由于克隆要求每个节点只能有一个备份(其实也只能做到一个备份),所以,对于已经有开辟空间的节点,我们只需要返回已经存在的节点即可。那怎么做到不重复呢?HashMap!只要我们为每个节点开辟一个空间的时候把这个空间指针保存在HashMap中,便可以通过查找HashMap来确定当前要克隆的节点是否已经存在,不存在再新开辟空间。

/**
 * Definition for undirected graph.
 * struct UndirectedGraphNode {
 *     int label;
 *     vector<UndirectedGraphNode *> neighbors;
 *     UndirectedGraphNode(int x) : label(x) {};
 * };
 */
class Solution {
public:
    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
        map<int,UndirectedGraphNode *> hashmap;
        return clone(node,hashmap);
        
    }
    
private:
    UndirectedGraphNode *clone (UndirectedGraphNode *node,map<int,UndirectedGraphNode * > &hashmap){
        if(node == NULL) return NULL;
        if(hashmap.find(node->label)!=hashmap.end()) return hashmap[node->label];
        UndirectedGraphNode *res = new UndirectedGraphNode (node->label);
        hashmap[node->label] = res ;
        for(int i = 0 ;i <node->neighbors.size();i++){
            UndirectedGraphNode *neib = clone(node->neighbors[i],hashmap);
            res->neighbors.push_back(neib);
        }
        return res ;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值