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

来源:互联网 发布:淘宝客服人工服务在线 编辑:程序博客网 时间:2024/05/18 17:58

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 ;    }};


原创粉丝点击