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


思路:用map存orignode和clone  node的对应关系。用queue存需要处理的节点。
当处理一个节点的neighbors时,首先先看这个neighbor已经在map里没,如果已经在,说明clone已经生成。只需要把这个clone加到复制node的neighbor里就好。否则,先new一个新的几点,加入到map中,放到neighbor里,原neighbor节点放入的需要处理的队列里。

 1 /**
 2  * Definition for undirected graph.
 3  * struct UndirectedGraphNode {
 4  *     int label;
 5  *     vector<UndirectedGraphNode *> neighbors;
 6  *     UndirectedGraphNode(int x) : label(x) {};
 7  * };
 8  */
 9 class Solution {
10 public:
11     UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
12         if(node==NULL)return NULL;
13         unordered_map<UndirectedGraphNode*,UndirectedGraphNode*> mp;
14         queue<UndirectedGraphNode*> visit;
15         UndirectedGraphNode* p=new UndirectedGraphNode(node->label);
16         mp[node]=p;
17         visit.push(node);
18         while(!visit.empty())
19         {
20             UndirectedGraphNode* cur=visit.front();
21             visit.pop();
22             for(int i=0;i<cur->neighbors.size();i++)
23             {
24                 UndirectedGraphNode* orig=cur->neighbors[i];
25                 if(mp.find(orig)==mp.end())
26                 {
27                     
28                     UndirectedGraphNode* clone=new UndirectedGraphNode(orig->label);
29                     mp[orig]=clone;
30                     mp[cur]->neighbors.push_back(clone);
31                     visit.push(orig);
32                 }else
33                 {
34                     mp[cur]->neighbors.push_back(mp[orig]);
35                 }
36             }
37         }
38         return p;
39     }
40 };

 

posted @ 2014-07-06 13:29  Hicandyman  阅读(122)  评论(0)    收藏  举报