-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathclone-graph.cpp
32 lines (28 loc) · 897 Bytes
/
clone-graph.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//Runtime: 36 ms
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if(!node) return NULL;
queue<UndirectedGraphNode*> Q;
map<UndirectedGraphNode*, UndirectedGraphNode* > Mp;
UndirectedGraphNode* copy = new UndirectedGraphNode(node->label);
Mp[node] = copy;
Q.push(node);
while(!Q.empty())
{
UndirectedGraphNode* t = Q.front();
Q.pop();
for(UndirectedGraphNode* crawl:t->neighbors)
{
if(Mp.find(crawl) == Mp.end())
{
UndirectedGraphNode* newnode = new UndirectedGraphNode(crawl->label);
Mp[crawl] = newnode;
Q.push(crawl);
}
Mp[t]->neighbors.push_back(Mp[crawl]);
}
}
return copy;
}
};