Skip to content

Commit 6e258a5

Browse files
committed
3
1 parent 0db08f5 commit 6e258a5

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

CloneGraph/CloneGraph.cc

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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* clone(UndirectedGraphNode* node, map<UndirectedGraphNode*, UndirectedGraphNode*>& graph) {
12+
if (node == NULL) {
13+
return NULL;
14+
}
15+
if (graph.find(node) != graph.end()) {
16+
return graph[node];
17+
}
18+
UndirectedGraphNode* newnode = new UndirectedGraphNode(node->label);
19+
graph[node] = newnode;
20+
for (int i = 0; i < node->neighbors.size(); i++) {
21+
UndirectedGraphNode* next = clone(node->neighbors[i], graph);
22+
newnode->neighbors.push_back(next);
23+
}
24+
return newnode;
25+
}
26+
27+
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
28+
map<UndirectedGraphNode*, UndirectedGraphNode*> graph;
29+
return clone(node, graph);
30+
}
31+
};

0 commit comments

Comments
 (0)