Clone an undirected graph. Each node in the graph contains a label
and a list of its neighbors
.
How we serialize an undirected graph:
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 #
.
- First node is labeled as
0
. Connect node0
to both nodes1
and2
. - Second node is labeled as
1
. Connect node1
to node2
. - Third node is labeled as
2
. Connect node2
to node2
(itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1
/
/
0 --- 2
/
\_/
Example
return a deep copied graph.
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 * @param node: A undirected graph node 13 * @return: A undirected graph node 14 */ 15 UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { 16 // write your code here 17 18 // suppose the value of nodes are unique. 19 // For every node, construct a new node of the same value. For its neighbours, first check if the neighbour has been created (value equals or not), if not, create a node and push into a queue, if so, link the it to the neighbor. 20 // To check whether the neighbour has been visited, maintain a hash map to map the original node to a newly created node. 21 if (!node) return node; 22 queue<UndirectedGraphNode* > qu; 23 qu.push(node); 24 unordered_map<UndirectedGraphNode*, UndirectedGraphNode* > um; 25 UndirectedGraphNode* result = new UndirectedGraphNode(node->label); 26 um[node] = result; 27 while (!qu.empty()) { 28 UndirectedGraphNode* temp = qu.front(); 29 qu.pop(); 30 UndirectedGraphNode* move = um[temp]; 31 32 for (auto neighbor : temp->neighbors) { 33 // if the neighbor is not created, created it and map neighbor to a new create node, update the neighbor of move with newly created node 34 if (um.find(neighbor) == um.end()) { 35 UndirectedGraphNode* newNeighbor = new UndirectedGraphNode(neighbor->label); 36 um[neighbor] = newNeighbor; 37 move->neighbors.push_back(newNeighbor); 38 qu.push(neighbor); 39 } else { 40 move->neighbors.push_back(um[neighbor]); 41 } 42 } 43 } 44 return result; 45 } 46 };