Skip to content

Commit 2528c94

Browse files
committed
133. Clone Graph
1 parent 86b6069 commit 2528c94

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

clone-graph.cpp

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
//Runtime: 36 ms
2+
class Solution {
3+
public:
4+
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
5+
6+
if(!node) return NULL;
7+
queue<UndirectedGraphNode*> Q;
8+
map<UndirectedGraphNode*, UndirectedGraphNode* > Mp;
9+
UndirectedGraphNode* copy = new UndirectedGraphNode(node->label);
10+
Mp[node] = copy;
11+
Q.push(node);
12+
13+
while(!Q.empty())
14+
{
15+
UndirectedGraphNode* t = Q.front();
16+
Q.pop();
17+
18+
for(UndirectedGraphNode* crawl:t->neighbors)
19+
{
20+
if(Mp.find(crawl) == Mp.end())
21+
{
22+
UndirectedGraphNode* newnode = new UndirectedGraphNode(crawl->label);
23+
Mp[crawl] = newnode;
24+
Q.push(crawl);
25+
}
26+
Mp[t]->neighbors.push_back(Mp[crawl]);
27+
}
28+
}
29+
30+
return copy;
31+
}
32+
};

0 commit comments

Comments
 (0)