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
         / \
         \_/

思考: 实现深度复制,但会出现环形,避免每个节点多次复制,可以将已经复制过的节点进行保存,label是唯一确定的,所以用label和node联系起来,然后进行递归即可。
java代码:
  1. Map<Integer,UndirectedGraphNode> mp = new HashMap<Integer,UndirectedGraphNode>();
  2. UndirectedGraphNode helper(UndirectedGraphNode node,Map<Integer,UndirectedGraphNode> mp) {
  3. if(node==null) return null;
  4. if(mp.containsKey(node.label)) return mp.get(node.label);
  5. UndirectedGraphNode new_node = new UndirectedGraphNode(node.label);
  6. mp.put(node.label,new_node);
  7. for(int i=0;i<node.neighbors.size();i++) {
  8. UndirectedGraphNode child = cloneGraph(node.neighbors.get(i));
  9. new_node.neighbors.add(child);
  10. }
  11. return new_node;
  12. }
  13. public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
  14. if(node == null) return null;
  15. UndirectedGraphNode new_node = helper(node,mp);
  16. return new_node;
  17. }
C++代码:
  1. UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
  2. UndirectedGraphNode *root =NULL;
  3. if(node==NULL) return root;
  4. unordered_map<int,UndirectedGraphNode *> track;
  5. root = cloneGraph(node,track);
  6. return root;
  7. }
  8. UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node, unordered_map<int,UndirectedGraphNode *> & track) {
  9. if(!node) return NULL;
  10. if(track.count(node->label)) return track[node->label];
  11. UndirectedGraphNode *root = new UndirectedGraphNode(node->label);
  12. root->neighbors.resize(node->neighbors.size());
  13. //root->label=node->label;
  14. track[node->label]=root;
  15. for(int i=0;i<node->neighbors.size();i++) {
  16. root->neighbors[i] = cloneGraph(node->neighbors[i],track);
  17. }
  18. return root;
  19. }
 
posted @ 2014-08-01 11:07  purejade  阅读(87)  评论(0编辑  收藏  举报