Skip to content

Commit e055084

Browse files
committed
Create Clone_Graph.cc
Add Clone Graph.
1 parent 729ce5a commit e055084

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Clone_Graph.cc

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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 *cloneGraph(UndirectedGraphNode *node) {
12+
// Note: The Solution object is instantiated only once and is reused by each test case.
13+
if (node == NULL)
14+
return NULL;
15+
UndirectedGraphNode *ret = new UndirectedGraphNode(node->label);
16+
17+
map<UndirectedGraphNode *, UndirectedGraphNode *> mp;
18+
mp[node] = ret;
19+
queue<UndirectedGraphNode *> que;
20+
que.push(node);
21+
22+
UndirectedGraphNode *tmp = NULL, *nxt = NULL;
23+
while (!que.empty()) {
24+
tmp = que.front();
25+
que.pop();
26+
for (int i = 0; i < (tmp->neighbors).size(); i++) {
27+
nxt = (tmp->neighbors)[i];
28+
if (mp.find(nxt) == mp.end()) {
29+
mp[nxt] = new UndirectedGraphNode(nxt->label);
30+
que.push(nxt);
31+
}
32+
(mp[tmp]->neighbors).push_back(mp[nxt]);
33+
}
34+
}
35+
return ret;
36+
}
37+
};

0 commit comments

Comments
 (0)