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 from 0 to N - 1, where N is the total nodes in the graph.
We use # as a separator for each node, and , as a separator for each neighbor of the node.
As an example, consider the serialized graph {1,2#2#2}.
The graph has a total of three nodes, and therefore contains three parts as separated by #.
Connect node 0 to both nodes 1 and 2.
Connect node 1 to node 2.
Connect node 2 to node 2 (itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1
/
/
0 --- 2
/
\_/
Solution: 1. DFS. 2. BFS.
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 12 // BFS 13 UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { 14 if(!node) { 15 return NULL; 16 } 17 unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> map; 18 queue<UndirectedGraphNode*> q; 19 q.push(node); 20 map[node] = new UndirectedGraphNode(node->label); 21 22 while(!q.empty()) { 23 UndirectedGraphNode* orgnode = q.front(); 24 q.pop(); 25 UndirectedGraphNode* newnode = map[orgnode]; 26 for(int i = 0; i < orgnode->neighbors.size(); i++) { 27 UndirectedGraphNode* orgneighbor = orgnode->neighbors[i]; 28 if(map.find(orgneighbor) == map.end()) { 29 UndirectedGraphNode* newneighbor = new UndirectedGraphNode(orgneighbor->label); 30 map[orgneighbor] = newneighbor; 31 q.push(orgneighbor); 32 } 33 newnode->neighbors.push_back(map[orgneighbor]); 34 } 35 } 36 return map[node]; 37 } 38 };