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 #.
First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
Second node is labeled as 1. Connect node 1 to node 2.
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
/ \
\_/
Code
void DFS_cg(UndirectedGraphNode *v1,UndirectedGraphNode *v2,map<UndirectedGraphNode *,UndirectedGraphNode *>& nodeMap){
vector<UndirectedGraphNode *>::const_iterator it = v1->neighbors.begin();
for(; it != v1->neighbors.end(); ++it){
UndirectedGraphNode *w1 = *it;
if(nodeMap.find(w1) == nodeMap.end()){
UndirectedGraphNode *w2 = new UndirectedGraphNode(w1->label);
v2->neighbors.push_back(w2);
nodeMap.insert(make_pair(w1,w2));
DFS_cg(w1,w2,nodeMap);
}
else{
UndirectedGraphNode *w2 = nodeMap[w1];
v2->neighbors.push_back(w2);
}
}
}
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(!node)
return 0;
map<UndirectedGraphNode *,UndirectedGraphNode *> nodeMap;
UndirectedGraphNode *u = new UndirectedGraphNode(node->label);
nodeMap.insert(make_pair(node,u));
DFS_cg(node,u,nodeMap);
return u;
}
No comments:
Post a Comment