Clone Graph -- LeetCode
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 #
.
- 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
/ \
\_/
思路:DFS。
要点:用一个map记录所有的label与指针的pair。这样可以避免环以及创建重复的节点。
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 //suppose these two node are already labelled 12 void help(UndirectedGraphNode *originalNode, UndirectedGraphNode *copiedNode, unordered_map<int, UndirectedGraphNode*> &dict) { 13 for (int i = 0; i < originalNode->neighbors.size(); i++) { 14 int childLabel = originalNode->neighbors[i]->label; 15 if (dict.count(childLabel) > 0) copiedNode->neighbors.push_back(dict[childLabel]); 16 else { 17 UndirectedGraphNode *node = new UndirectedGraphNode(childLabel); 18 dict.insert(make_pair(childLabel, node)); 19 copiedNode->neighbors.push_back(node); 20 help(originalNode->neighbors[i], node, dict); 21 } 22 } 23 } 24 UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { 25 if (node == NULL) return NULL; 26 unordered_map<int, UndirectedGraphNode*> dict; 27 UndirectedGraphNode *copiedNode = new UndirectedGraphNode(node->label); 28 dict.insert(make_pair(node->label, copiedNode)); 29 help(node, copiedNode, dict); 30 return copiedNode; 31 } 32 };